авторизация не работает (Spring Security) - PullRequest
1 голос
/ 07 июня 2019

Я хочу реализовать одну вещь в моем проекте, но она не работает. У меня есть страница JSP со списком студентов (allStudents.jsp), я хочу, чтобы при запуске проекта появлялась страница входа в систему, а после этого администратор вводил свой логин и пароль только тогда, когда он мог сразу перейти на страницу, где список студентов. Но мой проект не просит меня ввести логин и пароль и сразу открывает страницу, где находится список студентов.

AuthorizationController.jsp

package adil.java.schoolmaven.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class  AuthorizationController{

    // If user will be successfully authenticated he/she will be taken to the login secure page.
    @RequestMapping(value="/admin", method = RequestMethod.GET)
    public ModelAndView adminPage() {

        ModelAndView m = new ModelAndView();
        m.addObject("title", "You have successfully logged in.");
        m.addObject("message", "Home");
        m.setViewName("admin");

                return new ModelAndView("redirect: allStudents");

    }

    // Spring security will see this message.
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(@RequestParam(value = "error", required = false) String error, 
            @RequestParam(value = "logout", required = false) String logout) {

        ModelAndView m = new ModelAndView();
        if (error != null) {
            m.addObject("error", "Invalid username and password");      
        }

        if (logout != null) {
            m.addObject("msg", "you successfully logged out");      
        }

        m.setViewName("login");

                 return new ModelAndView("redirect: allStudents");
    }
}

Студенческий контроллер

package adil.java.schoolmaven.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletContext;
import adil.java.schoolmaven.entity.Student;
import adil.java.schoolmaven.service.StudentService;
import java.nio.file.FileSystemException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class StudentController {

    @Autowired
    private ServletContext servletContext;

    // Constructor based Dependency Injection
    private StudentService studentService;

    public StudentController() {

    }

    @Autowired
    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }




    @RequestMapping(value = "/allStudents", method = {RequestMethod.GET, RequestMethod.POST})

    public ModelAndView displayAllUser() {
        System.out.println("User Page Requested : All Students");
        ModelAndView mv = new ModelAndView();
        List<Student> studentList = studentService.getAllStudents();
        mv.addObject("studentList", studentList);
        mv.setViewName("allStudents");
        return mv;
    }

    @RequestMapping(value = "/addStudent", method = RequestMethod.GET)
    public ModelAndView displayNewUserForm() {
        ModelAndView mv = new ModelAndView("addStudent");
        mv.addObject("headerMessage", "Add Student Details");
        mv.addObject("student", new Student());
        return mv;
    }

    @PostMapping(value = "/addStudent")
    public String saveNewStudent(@RequestParam("name") @NonNull String name,
            @RequestParam("surname") @NonNull String surname,
            @RequestParam("avatar") MultipartFile file)
            throws IOException {

        Student student = new Student();
        student.setSurname(surname);
        student.setName(name);

        if (file != null && !file.isEmpty()) {
            student.setAvatar(studentService.saveAvatarImage(file).getName());
        }

        studentService.saveStudent(student);
        return "redirect:/allStudents";
    }

    @GetMapping(value = "/editStudent/{id}")
    public ModelAndView displayEditUserForm(@PathVariable Long id) {
        ModelAndView mv = new ModelAndView("editStudent");
        Student student = studentService.getStudentById(id);
        mv.addObject("headerMessage", "Редактирование студента");
        mv.addObject("student", student);
        return mv;
    }

    @PostMapping(value = "/editStudent")
    public String saveEditedUser(
            @RequestParam("id") Long id,
            @RequestParam("name") String name,
            @RequestParam("surname") String surname,
            @RequestParam("avatar") MultipartFile file) {

        try {

            studentService.updateStudent(name, surname, file, studentService.getStudentById(id));

        } catch (FileSystemException ex) {
            ex.printStackTrace();
        } catch (IOException e) {
            return "redirect:/error";
        }

        return "redirect:/allStudents";
    }

    @GetMapping(value = "/deleteStudent/{id}")
    public ModelAndView deleteUserById(@PathVariable Long id) {
        studentService.deleteStudentById(id);
        ModelAndView mv = new ModelAndView("redirect:/allStudents");

        return mv;

    }

}

MVC-dispacther-serlvet

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="adil.java.schoolmaven" />

    <!-- Resolves Views Selected For Rendering by @Controllers to *.jsp Resources in the /WEB-INF/ Folder -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

login.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Custom login</title>
        <style type="text/css">
            .error {
                color: #ff0000;
                font-weight: bold;
            }           
            .msg {
                color: #008000;
                font-weight: bold;
            }
        </style>
    </head>
    <body>
        <h1 id="banner">Custom login form</h1>

        <!-- invalid credentials error msg -->
        <c:if test="${not empty error}">
            <div class="error">${error}</div>
        </c:if>

        <!-- logged out msg -->
        <c:if test="${not empty msg}">
            <div class="msg">${msg}</div>
        </c:if>

        <!-- custom login form -->
        <form name="loginform" action="<c:url value='/login'/>" method="POST">
            <table>
                <tr>
                    <td>Логин:</td>     <!-- Enter username -->
                    <td><input type='text' name='username' value=''></td>
                </tr>
                <tr>
                    <td>Пароль:</td>            <!-- Enter password -->
                    <td><input type='password' name='password' /></td>
                </tr>
                <tr>
                    <td colspan="2">&nbsp;</td>
                </tr>
                <tr>
                    <td colspan='2'><input name="submit" type="submit" value="Submit" /></td>
                </tr>
            </table>
        </form>
    </body>
</html>

admin.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" session="true" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Secure page</title>    
    </head>
    <body>
        <h1>Title : ${title}</h1>
        <h1>Message : ${message}</h1>

        <!-- displaying the logged in user details. -->
        <c:if test="${pageContext.request.userPrincipal.name != null}">         
           <span>Welcome: ${pageContext.request.userPrincipal.name}</span> | <span><a id="logout" href="${pageContext.servletContext.contextPath}/logout">Logout</a></span>
        </c:if>
    </body>
</html>

введите описание изображения здесь

1 Ответ

0 голосов
/ 07 июня 2019

Вам необходимо настроить класс Spring Security Config, который реализует WebSecurityConfigurerAdapter. И настройте свою страницу входа в качестве параметра. Пожалуйста, см. мой код для справки. А также пройдите этот урок и попробуйте реализовать его. Это даст вам хорошие знания о том, как настроить вещи.

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    private final MyUserDetailsService userDetailsService;

    private final CustomBasicAuthenticationEntryPoint customBasicAuthenticationEntryPoint;

    @Autowired
    public SecurityConfig(MyUserDetailsService userDetailsService, CustomBasicAuthenticationEntryPoint customBasicAuthenticationEntryPoint)
    {
        this.userDetailsService = userDetailsService;
        this.customBasicAuthenticationEntryPoint = customBasicAuthenticationEntryPoint;
}
@Override
    public void configure(AuthenticationManagerBuilder auth)
    {
        auth.authenticationProvider(getDaoAuthenticationProvider());
    }

    @Bean
    public CustomDaoAuthenticationProvider getDaoAuthenticationProvider()
    {
        CustomDaoAuthenticationProvider daoAuthenticationProvider=new CustomDaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(getBCryptPasswordEncoder());
        return daoAuthenticationProvider;
    }

    /* BCrypt strength should 12 or more*/
    @Bean
    public PasswordEncoder getBCryptPasswordEncoder()
    {
        return new BCryptPasswordEncoder(12);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
            http.authorizeRequests()
                    .antMatchers("/anonymous*").anonymous()
                    .antMatchers("/register").permitAll()
                    .antMatchers("/users/**").hasAuthority(AuthorityConstants.ADMIN)
                    .antMatchers("/admin**").hasAuthority(AuthorityConstants.ADMIN)
                    .antMatchers("/profile/**").hasAuthority(AuthorityConstants.USER)
                    .antMatchers("/api/**").hasAnyAuthority(AuthorityConstants.API_USER,AuthorityConstants.ADMIN)
                    .antMatchers("/dba/**").hasAuthority(AuthorityConstants.DBA)
                    .anyRequest().authenticated()
            .and()
                    .httpBasic()
            .and()
                    .exceptionHandling()
                    .authenticationEntryPoint(customBasicAuthenticationEntryPoint)
            .and()
                    .formLogin()
                        .loginPage("/login")
                        .loginProcessingUrl("/login")
                    .successHandler(new CustomAuthenticationSuccessHandler(sessionHistoryRepository))
                    .failureHandler(new CustomAuthenticationFailureHandler(failedLoginRepository))
                        .permitAll()
                    .and()
                    .logout()
                        .deleteCookies("X-Auth-Token")
                        .clearAuthentication(true)
                        .invalidateHttpSession(true)
                        .logoutSuccessHandler(new CustomLogoutSuccessHandler())
                        .permitAll()
             .and()
                    .exceptionHandling()
                    .accessDeniedHandler(new CustomAccessDeniedHandler(unauthorizedRequestRepository))
            .and()
                    .rememberMe().rememberMeServices(springSessionRememberMeServices());

        // Uses CorsConfigurationSource bean defined below
        http.cors();

        http.sessionManagement()
                        //.invalidSessionUrl("/login.html")
                        //.invalidSessionStrategy((request, response) -> request.logout())
                        .sessionFixation().migrateSession()
                        .maximumSessions(1)
                        .maxSessionsPreventsLogin(false)
                        .sessionRegistry(sessionRegistry());

        http.csrf()
            .disable();
        http.authorizeRequests()
            .antMatchers("/").permitAll()
                .and()
            .authorizeRequests().antMatchers("/console/**","/h2-console/**").permitAll();
        http.headers()
             .frameOptions().disable();

    }

    @Bean
    public SpringSessionRememberMeServices springSessionRememberMeServices()
    {
        SpringSessionRememberMeServices rememberMeServices = new SpringSessionRememberMeServices();
        rememberMeServices.setRememberMeParameterName("remember-me");
        rememberMeServices.setValiditySeconds(ApplicationConstants.REMEMBERMETIMEOUT);
        return rememberMeServices;
    }

    //Cors filter to accept incoming requests
   @Bean
    CorsConfigurationSource corsConfigurationSource()
    {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.applyPermitDefaultValues();
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }


    @Override
    public void configure(WebSecurity web) throws Exception
    {
        web
            .ignoring()
            .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**","/h2-console/**","/console/**");
    }


    @Bean("authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }

    @Bean
    public SessionRegistry sessionRegistry()
    {
        return new SessionRegistryImpl();
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...