Spring Security 03 认证处理器

自定义资源规则权限

Spring Security 5.7.0 弃用了 WebSecurityConfigurerAdapter

官网博客链接地址:

Spring Security without the WebSecurityConfigurerAdapter

5.7.0 之前的配置 

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeHttpRequests()
			.mvcMatchers("/index").permitAll()
			.anyRequest().authenticated()
			.and().formLogin();
	}
}

5.7.0 之后的配置

@Configuration
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .mvcMatchers("/index")  // 注意: 放⾏资源必须放在所有认证请求之前!
                .permitAll() // 代表放⾏该资源,该资源为公共资源 ⽆需认证和授权可以直接访问
                .anyRequest().authenticated() // 代表所有请求,必须认证之后才能访问
                .and().formLogin(); // 代表开启表单认证
        return http.build();
    }
}

自定义登入成功 / 失败处理

由于现在项目都为前后端分离,所以这里展示页面跳转情况,如有需求,B站搜索:编程不良人

在前后端分离开发中就不需要成功之后跳转⻚⾯。只需要给前端返回⼀个 apiKey。

public interface AuthenticationSuccessHandler {

	/**
	 * Called when a user has been successfully authenticated.
	 * @param request the request which caused the successful authentication
	 * @param response the response
	 * @param chain the {@link FilterChain} which can be used to proceed other filters in
	 * the chain
	 * @param authentication the <tt>Authentication</tt> object which was created during
	 * the authentication process.
	 * @since 5.2.0
	 */
	default void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
			Authentication authentication) throws IOException, ServletException {
		onAuthenticationSuccess(request, response, authentication);
		chain.doFilter(request, response);
	}

	/**
	 * Called when a user has been successfully authenticated.
	 * @param request the request which caused the successful authentication
	 * @param response the response
	 * @param authentication the <tt>Authentication</tt> object which was created during
	 * the authentication process.
	 */
	void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException;

}

根据接⼝的描述信息,也可以得知登录成功会⾃动回调这个⽅法,进⼀步查看它的默认实现,你会发现successForwardUrl、 defaultSuccessUrl也是由它的⼦类实现的

public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg", "登入成功");
        map.put("status", 200);
        map.put("code", "apiKey");
        response.setContentType("application/json;charset=UTF-8");
        String json = new ObjectMapper().writeValueAsString(map);
        response.getWriter().println(json);
    }
} 

自定义登入失败处理类

public interface AuthenticationFailureHandler {

	/**
	 * Called when an authentication attempt fails.
	 * @param request the request during which the authentication attempt occurred.
	 * @param response the response.
	 * @param exception the exception which was thrown to reject the authentication
	 * request.
	 */
	void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException;

}
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg", "登入失败:" + exception.getMessage());
        map.put("status", 500);
        response.setContentType("application/json;charset=UTF-8");
        String json = new ObjectMapper().writeValueAsString(map);
        response.getWriter().println(json);
    }
}

总配置

@Configuration
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .mvcMatchers("/index")  
                .permitAll() 
                .anyRequest().authenticated() 
                .and().formLogin()
                .successHandler(new LoginSuccessHandler())
                .failureHandler(new LoginFailureHandler())
                .and().csrf().disable(); 
        return http.build();
    }
}

启动项目登入

 

注销登入

Spring Security 中也提供了默认的注销登录配置,在开发时也可以按照⾃⼰需求对注销进⾏个性化定制。

前后端分离开发,注销成功之后就不需要⻚⾯跳转了,只需要将注销成功的信息返回前端即可,此时我们可以通过⾃定义 LogoutSuccessHandler 实现来返回注销之后信息:

public class LogoutHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg", "注销成功" );
        map.put("status", 200);
        response.setContentType("application/json;charset=UTF-8");
        String json = new ObjectMapper().writeValueAsString(map);
        response.getWriter().println(json);
    }
}  
 	@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .mvcMatchers("/index")
                .permitAll()
                .anyRequest().authenticated()
                .and().formLogin()
                .successHandler(new LoginSuccessHandler())
                .failureHandler(new LoginFailureHandler())
                .and()
                .logout()
                .logoutRequestMatcher(
                        new OrRequestMatcher(
                                new AntPathRequestMatcher("/logout1", "GET"),
                                new AntPathRequestMatcher("/logout2", "GET")))
                .logoutSuccessHandler(new LogoutHandler());
        return http.csrf().disable().build();
    }

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值