前后端分类状态下SpringSecurity的玩法

前后端分离状态下,后端SpringSecurity该如何变动呢? 如何变动取决于前后端分离状态下,前后端交互的特点,纯json交互,闲言少叙,上干货

主配置类

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)// 开启基于方法级别的防护
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    SecurityService securityService;
    @Autowired
    MyAuthenticationFailHandler myAuthenticationFailHandler;
    @Autowired
    MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(securityService)
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Bean
    public AuthenticationEntryPoint macLoginUrlAuthenticationEntryPoint() {
        return new MacLoginUrlAuthenticationEntryPoint();
    }
    
    // 安全配置项
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.formLogin()
                .loginPage("/login123")
                .loginProcessingUrl("/user/login")// from表单中的action往这里提交
                .usernameParameter("username").passwordParameter("password").permitAll()
                .loginProcessingUrl("/login")
                .successHandler(myAuthenticationSuccessHandler).failureHandler(myAuthenticationFailHandler)
                .and()
                .exceptionHandling().authenticationEntryPoint( macLoginUrlAuthenticationEntryPoint())
                .and()
                .authorizeRequests()// 禁用了 springSecurity , 允许一切请求
                .antMatchers("/api/user/text1","/api/user/text2").hasRole("ADMIN")
                .antMatchers("/api/user/text3").hasRole("USRE")
                .anyRequest().permitAll() //
                .and().csrf().disable();// todo

    }
}

配置登录成功处理器,响应给前端json

在前后端没有分离时,用户完成了登录认证后,由后端的框架控制页面的跳转,但是前后端分离时,前后路由的跳转后端不能干涉, 只能给前端用户的信息等信息,由前端控制页面的跳转

@Component("MyAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    ObjectMapper mapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        System.err.println("登录成功  --- 返回json....");

        // 允许跨域
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        // 允许自定义请求头token(允许head跨域)
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");
        httpServletResponse.setContentType("application/json;charset=UTF-8");

        httpServletResponse.setStatus(200); // 成功返回200

        Result result = new Result(200, "登录成功", true, authentication.getPrincipal());

        // 登录成功
        httpServletResponse.getWriter().write(mapper.writeValueAsString(result));

    }

配置登录失败处理器,响应给前端json

登录失败,返回给前端失败信息,及状态码

@Component("MyAuthenticationFailHandler")
public class MyAuthenticationFailHandler implements AuthenticationFailureHandler {

    @Autowired
    ObjectMapper mapper;
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        System.err.println("登录失败   --  返回json....");

        // 允许跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 允许自定义请求头token(允许head跨域)
        response.setHeader("Access-Control-Allow-Headers", "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");
        response.setStatus(201);
        response.setContentType("application/json;charset=UTF-8");

        if (e instanceof BadCredentialsException ||
                e instanceof UsernameNotFoundException) {
            response.getWriter().write(mapper.writeValueAsString("用户名或密码错误"));   // 只返回异常消息
        } else if (e instanceof LockedException) {
            response.getWriter().write(mapper.writeValueAsString("账户被锁定,请联系管理员!"));   // 只返回异常消息
        } else if (e instanceof CredentialsExpiredException) {
            response.getWriter().write(mapper.writeValueAsString("账户被锁定,请联系管理员!"));   // 只返回异常消息
        } else if (e instanceof AccountExpiredException) {
            response.getWriter().write(mapper.writeValueAsString("账户过期,请联系管理员!"));   // 只返回异常消息
        } else if (e instanceof DisabledException) {
            response.getWriter().write(mapper.writeValueAsString("账户被禁用,请联系管理员!"));   // 只返回异常消息
        } else {
            response.getWriter().write(mapper.writeValueAsString("登录失败!"));   // 只返回异常消息
        }
    }
}

当用户没有任何权限时,相应给前端json

默认情况下,当用户没有权限时,springsecurity 会将默认的无权限的页面返回给前端,这个页面巨丑,还会覆盖原来的网页,加入这个配置类实现返回由前端友情json提示

public class MacLoginUrlAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    ObjectMapper mapper;
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        // 允许跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 允许自定义请求头token(允许head跨域)
        response.setHeader("Access-Control-Allow-Headers", "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");
        response.setStatus(202);

        response.setContentType("application/json;charset=UTF-8");

        response.getWriter().write(mapper.writeValueAsString("用户相应的无权限,请联系管理员"));   // 只返回异常消息
    }
posted @ 2019-09-15 19:52  赐我白日梦  阅读(1111)  评论(0编辑  收藏  举报