前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >0基础手撕SpringSecurity

0基础手撕SpringSecurity

作者头像
Tom2Code
发布2022-04-15 16:37:49
2630
发布2022-04-15 16:37:49
举报
文章被收录于专栏:Tom

项目需要,最近接触到了SpringSecurity

但是还没开始学原理

先记录一下吧

定义了三个handler均继承于 XXXHandler

CustomAuthenticationFailedHandler

继承

SimpleUrlAuthenticationFailureHandler

CustomAuthenticationSuccessHandler

继承

SavedRequestAwareAuthenticationSuccessHandler

CustomLogoutSuccessHandler

继承

LogoutSuccessHandler

直接上代码吧

1.CustomAuthenticationFailedHandler

代码语言:javascript
复制
package xx.xxx.workflow.security;

import xx.xxx.workflow.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 2 * @Author: AkaTom
 * 3 * @Date: 2022/2/16 11:26
 * 4 * 认证失败
 */
@Component
public class CustomAuthenticationFailedHandler extends SimpleUrlAuthenticationFailureHandler {

    //负责转化json
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        Result res = Result.build(HttpStatus.UNAUTHORIZED.value(), exception.getMessage());
        String s = objectMapper.writeValueAsString(res);
        response.getWriter().write(s);
    }
}

这是一个认证失败的security配置类

重写了onAuthenticationFailure方法,使返回值成为json格式的

并向浏览器输出json格式的信息

2.CustomAuthenticationSuccessHandler

代码语言:javascript
复制
package xx.xxx.workflow.security;

import xx.xxx.workflow.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 2 * @Author: AkaTom
 * 3 * @Date: 2022/2/16 11:18
 * 4 * 成功处理器:响应json结果给前端进行处理,比如跳转到首页
 */
@Component
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    //负责转化json
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication)
            throws ServletException, IOException {

        response.setContentType("application/json;charset=UTF-8");
        Result ok=Result.ok("认证成功");
        String s = objectMapper.writeValueAsString(ok);
        response.getWriter().write(s);
    }
}

这是一个处理成功的security的配置类,可以看到返回值也是json格式的

并向浏览器输出

3.CustomLogoutSuccessHandler

代码语言:javascript
复制
package xx.xx.workflow.security;

import xx.xxx.workflow.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 2 * @Author: AkaTom
 * 3 * @Date: 2022/2/16 14:01
 * 4 * 退出成功,响应json
 */
@Component("logoutSuccessHandler")
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {

    //负责转化json
    @Autowired
    ObjectMapper objectMapper;


    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        String json=objectMapper.writeValueAsString(Result.ok("退出成功"));
        httpServletResponse.getWriter().write(json);
    }
}

这是一个注销的配置类,还是向浏览器输出json格式的信息

最后是一个重头戏

这个配置类,把三者融合到了一起

4.SpringSecurityConfig

代码语言:javascript
复制
package xx.xxx.workflow.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

/**
 * 2 * @Author: AkaTom
 * 3 * @Date: 2022/2/16 13:27
 * 4
 */
@Configuration
@EnableWebSecurity//开启springsecurity认证配置
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService customUserDetailsService;

    @Autowired
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;

    @Autowired
    private CustomAuthenticationFailedHandler customAuthenticationFailedHandler;

    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;

    @Bean
    public PasswordEncoder passwordEncoder(){
        //明文加随机盐
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //1.认证管理器
        auth.userDetailsService(customUserDetailsService);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginProcessingUrl("/user/login")//默认 /login
                .successHandler(customAuthenticationSuccessHandler)
                .failureHandler(customAuthenticationFailedHandler)
            .and()
                .logout()
                .logoutUrl("/user/logout")
                .logoutSuccessHandler(logoutSuccessHandler)
            .and()
                .authorizeRequests()
                .anyRequest().authenticated()//所有请求都需要通过认证后才可以访问
            .and()
                .csrf().disable();//关闭跨站请求伪造
    }
}

这个就是security的核心了

但是目前还没彻底开始手撕

所以先记录一下吧

但是configure方法里的一些写法还是能看懂的

比如最后关闭了csrf,配置了三个handler

今天就先简短的记录一下这三个类和一个核心类

改日 手撕security的时候 再来温故

see ya

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-02-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Tom的小院 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档