SpringBoot-登陆表单详细配置(续HttpSecurity)


登陆表单详细配置


package org.akk.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("uuc").password("123").roles("admin")
                .and()
                .withUser("akk").password("123").roles("user");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("user/**").hasAnyRole("admin", "user")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                //这里就是处理登录的url,
                .loginProcessingUrl("/doLogin")
                //跳转的登录界面
                .loginPage("/login")
                .usernameParameter("name")
                .passwordParameter("passwd")
                //成功时的处理
                .successHandler(new AuthenticationSuccessHandler() {
                    //authentication中保存了登陆成功的用户信息
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                        httpServletResponse.setContentType("application/json;charset = utf-8");
                        PrintWriter out = httpServletResponse.getWriter();
                        Map<String, Object> map = new HashMap<>();
                        map.put("status", 200);
                        map.put("msg", authentication.getPrincipal());
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                //失败时的处理
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                        httpServletResponse.setContentType("application/json;charset = utf-8");
                        PrintWriter out = httpServletResponse.getWriter();
                        Map<String, Object> map = new HashMap<>();
                        map.put("status", 401);
                        if (e instanceof LockedException) {
                            map.put("msg", "账户被锁定,登陆失败");
                        } else if (e instanceof BadCredentialsException) {
                            map.put("msg", "用户名或者密码输入错误,登陆失败");
                        } else if (e instanceof DisabledException) {
                            map.put("msg", "账户被禁用,登陆失败");
                        } else if (e instanceof AccountExpiredException) {
                            map.put("msg", "账户过期,登陆失败");
                        } else if (e instanceof CredentialsContainer) {
                            map.put("msg", "密码过期,登陆失败");
                        }else{
                            map.put("msg","登陆失败");
                        }
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()
                .and()
                .csrf().disable();
    }
}
方法 行为
loginProcessingUrl 这里处理登陆的接口
loginPage 设置登录界面(自定义)
usernameParameter 自定义登录用的username别名
passwordParameter 自定义登录用的password别名。
successForwardUrl 登录成功的处理器(不是前后端分离)
successHandler 登录成功的处理器适用于前后端分离
failureHandler 登录失败的处理器适用于前后端分离

更多报错信息的实现
在这里插入图片描述
postman测试:
username和password也应为配置变成name和passwd
成功返回状态401
在这里插入图片描述
成功登录
在这里插入图片描述

"msg": {
//返回中自动抹去
        "password": null,
        "username": "akk",
        "authorities": [
            {
            //[ROLE_] Sercurity自动添加的
                "authority": "ROLE_user"
            }
        ],
        //账户没有过期
        "accountNonExpired": true,
         //账户没有锁定
        "accountNonLocked": true,
        //密码没有过期
        "credentialsNonExpired": true,
        //账户可用的
        "enabled": true
    },
    "status": 200
发布了35 篇原创文章 · 获赞 1 · 访问量 611

猜你喜欢

转载自blog.csdn.net/weixin_39232166/article/details/105325050