美文网首页
SpringSecurity开发基于表单的认证(三)

SpringSecurity开发基于表单的认证(三)

作者: 七颜即无 | 来源:发表于2020-09-07 16:10 被阅读0次

    个性化用户认证流程

    • 自定义登录页面
    • 自定义登陆成功处理
    • 自定义登录失败处理

    自定义登录页面

    之前我们使用SpringSecurity默认配置的登录页面,如表单登录或者HTTP BASIC登录,这里我们想自定义登录页面。首先我们修改安全配置:

    @Configuration
    public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter{
    
        @Bean
        public PasswordEncoder passwordEncoder(){
            return new BCryptPasswordEncoder();
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception{
            http.formLogin()
                .loginPage("/login.html")
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated();
        }
    }
    
    

    在configure方法中指定了登陆页面的URL后病并且在项目的/src/main/resources/下建一个resources文件夹,这个文件夹里面放的是项目的文件默认放置的路径,在这个文件夹目录下添加一个login.html登陆页面:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>登录</title>
    </head>
    <body>
        <h2>标准登录页面</h2>
    </body>
    </html>
    
    

    启动应用后,我们访问地址http://localhost://8080/user/1后页面显示:

    image

    导致这个错误的原因是:我们在实现BrowserSecurityConfig 类的方法中,设置了登录页面为login.html的同时也设置了身份认证,导致访问login.html页面(也是一次请求)的时候也进行身份认证,如此循环往复循环访问,错误提示重定向次数过多。为此我们修改代码如下:

        @Override
        protected void configure(HttpSecurity http) throws Exception{
            http.formLogin()
                .loginPage("/login.html")
                .and()
                .authorizeRequests()
                .antMatchers("/login.html").permitAll()
                .anyRequest()
                .authenticated();
        }
    
    

    添加的antMatchers("/login.html").permitAll()这句表示当请求url符合这个路径时不进行身份认证,修改后我们访问http://localhost://8080/user/1后默认就跳到了我们自己配置的login.html登录页面了。
    接下来我们对自定义的登录页面进行修改:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>登陆页面</title>
    </head>
    <body>
        <h2>标准登陆页面</h2>
        <h3>表单登录</h3>
        <form action="/authentication/form" method="post">
            <table>
                <tr>
                    <td>用户名:</td>
                    <td><input type="text" name="username"></td>
                </tr>
                <tr>
                    <td>密码:</td>
                    <td><input type="text" name="password"></td>
                </tr>
                <tr>
                    <td colspan="2"><button type="submit">登录</button></td>
                </tr>
            </table>
        </form>
    </body>
    </html>
    
    

    表单的属性action="/authentication/form" method="post"是我们自己定义的url。记得第一讲说过,表单登录的请求在SpringSecurity中是由UsernamePasswordAuthenticationFilter过滤器来处理的,这个过滤器类中:

        public UsernamePasswordAuthenticationFilter() {
            super(new AntPathRequestMatcher("/login", "POST"));
        }
    
    

    可见过滤器只处理url是:/login的POST请求,而我们修改后的登录页面提交时url是/authentication/form,为此我们需要在配置类中告诉SpringSecurity现在表单登录的请求url是多少:

        @Override
        protected void configure(HttpSecurity http) throws Exception{
            http.formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/authentication/form")
                .and()
                .authorizeRequests()
                .antMatchers("/login.html").permitAll()
                .anyRequest()
                .authenticated();
        }
    
    

    loginProcessingUrl("/authentication/form")这句代码就是设置登录请求的url路径。
    修改后我们重启应用,访问http://localhost://8080/user/1后默认跳出我们设置的登录页面:

    image

    填写正确的账号和密码后提交报错,如下:

    image

    这是由SpringSecurity默认的跨站伪造防护导致的,此处我们修改设置如下:

        @Override
        protected void configure(HttpSecurity http) throws Exception{
            http.formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/authentication/form")
                .and()
                .authorizeRequests()
                .antMatchers("/login.html").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf().disable();
        }
    
    

    修改后我们再次登录,这是表单登录页面填写正确的账号和密码后程序能访问到restful api了。
    修改后我们现在的情况是当我们在浏览器发起一个请求访问http://localhost://8080/user/1的时候,
    首先跳转到登录页面提示我们登录。但如果我们想访问url中末尾带html的,如http://localhost://8080/index.html的时候返回登录页面,而如果访问http://localhost://8080/user/1的时候返回错误码,为此我们需要新建一个自定义的控制器来对以html结尾的请求和非html结尾的请求进行区分,我们在控制器的方法中判断是否是html结尾的请求引发的跳转,如果是则返回登录页面,如果不是则返回401状态码和错误信息。
    下面我们新建一个控制器:

    @RestController
    public class BrowserSecurityController {
        private Logger logger = LoggerFactory.getLogger(getClass());
        private RequestCache requestCache = new HttpSessionRequestCache();
        private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
        @Autowired
        private SecurityProperties securityProperties;
        /**
         * 当需要身份认证时跳转到这里
         * @param request
         * @param response
         * @return
         * @throws IOException 
         */
        @RequestMapping("/authentication/require")
        @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
        public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException{
    
            SavedRequest savedRequest = requestCache.getRequest(request, response);
    
            if(savedRequest != null){
                String target = savedRequest.getRedirectUrl();
                logger.info("引发跳转的请求是:"+target);
                if(StringUtils.endsWithIgnoreCase(target, ".html")){
                    redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
                }
    
            }
            return new SimpleResponse("访问的服务需要身份认证,请引导用户到登录页面");
        }
    }
    
    

    当请求url符合“/authentication/require”的路径时访问上述控制器的requireAuthentication方法,这个方法通过RequestCache对象和SavedRequest对象获取保存在缓存中的请求url,如果请求url的后缀为.html,则页面重定向到securityProperties.getBrowser().getLoginPage()的返回值;否则返回状态码HttpStatus.UNAUTHORIZED,即401,并且提示“访问的服务需要身份认证,请引导用户到登录页面”。注:
    SimpleResponse类用于封装返回信息,使得以json格式返回,下面是这个SimpleResponse类的实现:

    public class SimpleResponse {
        public SimpleResponse(Object content){
            this.content = content;
        }
        private Object content;
        public Object getContent() {
            return content;
        }
        public void setContent(Object content) {
            this.content = content;
        }
    }
    
    

    那securityProperties.getBrowser().getLoginPage()具体是什么内容呢?
    是这样的,我们将以.html为末尾的请求对应的跳转页面配置到了项目的属性文件application.properties文件中:

    spring.security.browser.loginPage=/demo-signin.html
    
    

    我们将这个自己配的属性分成两层,一层是spring.security,另一层是spring.security下的browser。为了获取这个属性,编写类SecurityProperties获取前缀是spring.security的属性

    @ConfigurationProperties(prefix = "spring.security")
    public class SecurityProperties {
        private BrowserProperties browser = new BrowserProperties();
        public BrowserProperties getBrowser() {
            return browser;
        }
        public void setBrowser(BrowserProperties browser) {
            this.browser = browser;
        }   
    }
    
    

    @ConfigurationProperties(prefix = "spring.security")注解表示读取前缀是“spring.security”的属性。
    这个SecurityProperties 类中又有一个变量BrowserProperties browser保存属性文件中配的第三个字段browser的值,BrowserProperties对象的属性loginPage保存了第四个字段loginPage的值。下面是BrowserProperties类的具体实现:

    public class BrowserProperties {
            private String loginPage;
        public String getLoginPage() {
            return loginPage;
        }
        public void setLoginPage(String loginPage) {
            this.loginPage = loginPage;
        }   
    }
    
    

    为使SecurityProperties这个读取属性文件的类生效,需要再加一个配置类;

    @Configuration
    @EnableConfigurationProperties(SecurityProperties.class)
    public class SecurityCoreConfig {
    }
    
    

    通过以上配置来使能获取属性配置的类生效。

    最后我们修改登录行为:

    @Configuration
    public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter{
    
        @Autowired 
        SecurityProperties securityProperties;
    
        @Bean
        public PasswordEncoder passwordEncoder(){
            return new BCryptPasswordEncoder();
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception{
            http.formLogin()
                .loginPage("/authentication/require") //跳转的登录页
                .loginProcessingUrl("/authentication/form") //登录时的请求
                .and()
                .authorizeRequests()
                .antMatchers("/authentication/require",
                        securityProperties.getBrowser().getLoginPage()).permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf().disable();
        }
    }
    
    

    启动应用后,当我们访问访问http://localhost:8080/user/1的时候由于没有携带携带登录信息,跳转到我们设置的”/authentication/require“路径下,这个路径由我们刚设置的控制器来处理,末尾没有html信息,所以返回的401,并且提示”访问的服务需要身份认证,请引导用户到登录页面“,并且url跳转到/authentication/require。如果访问http://localhost:8080/index.html的时候,则跳转到securityProperties.getBrowser().getLoginPage()指定的demo-signin.html页面上。demo-signin.html代码如下:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>登录</title>
    </head>
    <body>
        <h2>demo 登录页</h2>
    </body>
    </html>
    
    

    自定义登录成功页面

    当我们访问http://localhost:8080/user/1的时候先会跳到表单登录页,填写完账号密码登陆成功后,会默认跳转到/user/1请求对应的控制器上,这一步是SpringSecurity默认的处理类来处理的,如果我们想登陆成功后不执行默认的操作,而是实现我们需要的操作,就要了解一下接下来的内容。
    自定义登录成功页面需要实现AuthenticationSuccessHandler接口:

    @Component
    public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    
        private Logger logger = LoggerFactory.getLogger(getClass());
    
        @Autowired
        private ObjectMapper objectMapper;
    
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
            //Authentication接口封装认证信息
    
            logger.info("登录成功");
    
            response.setContentType("application/json;charset=UTF-8");
    
            //将authentication认证信息转换为json格式的字符串写到response里面去
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        }
    }
    
    

    我们在接口的AuthenticationSuccessHandler方法中将认证信息放到response信息中。
    此外我们要使用这个自定义的登陆成功处理类,而不是使用默认的处理人,需要修改登陆行为配置类:

    @Configuration
    public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter{
    
        @Autowired 
        SecurityProperties securityProperties;
    
        @Autowired
        private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    
        @Bean
        public PasswordEncoder passwordEncoder(){
            return new BCryptPasswordEncoder();
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception{
            http.formLogin()
                .loginPage("/authentication/require") //跳转的登录页
                .loginProcessingUrl("/authentication/form") //登录时的请求
                .successHandler(myAuthenticationSuccessHandler) //表单登录成功时使用我们自己写的处理类
                .and()
                .authorizeRequests()
                .antMatchers("/authentication/require",
                        securityProperties.getBrowser().getLoginPage()).permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf().disable();
        }
    }
    
    

    通过引入MyAuthenticationSuccessHandler对象,并使用successHandler方法将其设置为登录成功的处理类。
    这样启动应用后,表单登录填写完账号密码登陆成功后,页面显示我们塞到response中的认证信息:

    image image

    其中authenticated=true表示已经经过身份认证,authorities:admin等表示用户的权限是admin,credentials表示密码,一般springsecurity做了处理,不会返回到前台,所以为空,最重要的是printcipal中的内容,里面有我们之前在UserDetail类中设置的四个布尔值等信息。

    自定义登录失败处理

    相应的,登录失败的处理要实现的接口是

    @Component
    public class MyAuthenticationFailHandler implements AuthenticationFailureHandler {
        private Logger logger = LoggerFactory.getLogger(getClass());
    
        @Autowired
        private ObjectMapper objectMapper;
    
        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException exception) throws IOException, ServletException {
    
            logger.info("登陆失败");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(exception));
        }
    }
    
    

    实现方法中第三个方法不是认证信息而是登录失败的异常对象,我们选中AuthenticationException,然后右键选择open hierarchy查看类的继承图:

    image

    由上图可以发现,这个异常继承了很多其他异常,如UsernameNotFoundException异常(请求中没有用户名和密码),BadCredentialsException异常(账号密码错误)。
    在onAuthenticationFailure处理方法中我们将错误信息返回,启动应用后,如果输入错误的账号密码后登陆,页面显示如下:

    image

    打印出来的都是错误的堆栈信息。

    扩展

    我们在上面设计了登录成功和登录失败后的自定义处理类,但是如果执行了自定义处理类后,就不会执行默认的处理类的跳转到原来url的逻辑,为此我们可以继承springsecurity的默认处理类,并且加上配置来确定是否要跳转或是执行自定义行为,修改后的代码如下:

    @Component
    public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    
        private Logger logger = LoggerFactory.getLogger(getClass());
    
        private LoginType loginType = LoginType.JSON;
    
        @Autowired
        private ObjectMapper objectMapper;
    
        @Autowired
        private SecurityProperties securityProperties;
    
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
            //Authentication接口封装认证信息
    
            logger.info("登录成功");
    
            if(loginType.equals(securityProperties.getBrowser().getLoginType())){
                response.setContentType("application/json;charset=UTF-8");
    
                //将authentication认证信息转换为json格式的字符串写到response里面去
                response.getWriter().write(objectMapper.writeValueAsString(authentication));
            }
            else{
                super.onAuthenticationSuccess(request, response, authentication);
            }
        }
    }
    
    

    此时登录处理器MyAuthenticationSuccessHandler继承的类MyAuthenticationSuccessHandler已经实现了AuthenticationSuccessHandler接口,并且MyAuthenticationSuccessHandler就是springsecurity默认登录成功的处理器。代码中的LoginType是一个枚举,实现如下:

    public enum LoginType {
        REDIRECT,
        JSON
    }
    
    

    此外,在application.properties属性文件中又加上一个配置项:

    spring.security.browser.loginType=REDIRECT
    
    

    用于配置是否是执行框架的默认的行为还是执行我们的自定义行为。并在BrowserProperties类中加上这个属性,便于获取到这个属性。所以执行结果是,当我们在属性文件中配置了REDIRECT后,如果登录成功后,就会执行父类的onAuthenticationSuccess方法,即框架的默认行为,如果设置了JSON,登录成功后,就会执行自定义的response填入JSON数据返回给也页面的行为。这样想选哪种只需要修改属性文件就行。
    同理,我们修改处理登录失败的代码如下:

    @Component
    public class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {
    
        private Logger logger = LoggerFactory.getLogger(getClass());
    
        private LoginType loginType = LoginType.JSON;
    
        @Autowired
        private ObjectMapper objectMapper;
    
        @Autowired
        private SecurityProperties securityProperties;
    
        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException exception) throws IOException, ServletException {
    
            if(loginType.equals(securityProperties.getBrowser().getLoginType())){
                logger.info("登陆失败");
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(objectMapper.writeValueAsString(exception));
            }
            else{
                super.onAuthenticationFailure(request, response, exception);
            }
    
        }
    
    }
    
    

    修改后的登录成功失败后的逻辑就会变得更加灵活了。

    转载自:云师兄
    链接:https://www.jianshu.com/p/7a57405f36dc

    相关文章

      网友评论

          本文标题:SpringSecurity开发基于表单的认证(三)

          本文链接:https://www.haomeiwen.com/subject/gqklektx.html