简体   繁体   English

授权不起作用(Spring Security)

[英]authorization does not work (Spring Security)

I want to implement one thing in my project, but it does not work. 我想在我的项目中实现一件事,但是没有用。 I have a jsp page with a list of students(allStudents.jsp), I want when the project starts so that the login page comes out and after such as the admin enters his login and password only when he could immediately go to the page where the list of students. 我有一个带有学生列表的jsp页面(allStudents.jsp),我想在项目启动时让登录页面出来,然后,例如admin,只有当他可以立即进入该页面时,他才输入登录名和密码学生名单。 But my project does not ask me to enter my login and password and immediately opens the page where the list of students is. 但是我的项目不要求我输入登录名和密码,而是立即打开学生列表所在的页面。

AuthorizationController.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");
    }
}

Student Controller 学生主管

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 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 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 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>

enter image description here 在此处输入图片说明

You need to configure Spring Security Config class that implements WebSecurityConfigurerAdapter. 您需要配置实现WebSecurityConfigurerAdapter的Spring Security Config类。 And configure your login page as a parameter. 并将您的登录页面配置为参数。 Please see my code for reference. 请参阅我的代码以供参考。 And also go through this tutorial and try to implement it. 并仔细阅读本教程并尝试实现它。 It will give you good knowledge on how to setup things. 它将为您提供有关如何进行设置的良好知识。

SecurityConfig.java 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();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM