码迷,mamicode.com
首页 > 编程语言 > 详细

Spring Security

时间:2021-01-25 11:03:03      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:repos   sse   basic   autowire   pass   页面   check   ons   VID   

Spring Security基于Spring框架,提供了一套Web应用安全性的完整解决方案。JWT(JSON Web Token)是当前比较主流的Token令牌生成方案,非常适合作为登录和授权认证的凭证。这里我们就使用Spring Security并结合JWT实现用户认证(Authentication)和用户授权(Authorization)两个主要部分的安全内容。

1.添加依赖
在mango-admin下的pom文件中添加Spring Security和JWT依赖包

2.添加配置

在config包下新建一个Spring Security的配置类WebSecurityConfig,主要是进行一些安全相关的配置,比如权限URL匹配策略、认证过滤器配置、定制身份验证组件、开启权限认证注解等

@Configuration
@EnableWebSecurity // 开启Spring Security
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启权限注解,如:@PreAuthorize注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
@Autowired
private UserDetailsService userDetailsService;
 
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
// 使用自定义身份验证组件
auth.authenticationProvider(new JwtAuthenticationProvider(userDetailsService));
}
 
@Override
protected void configure(HttpSecurity http) throws Exception {
// 禁用 csrf, 由于使用的是JWT,我们这里不需要csrf
http.cors().and().csrf().disable()
.authorizeRequests()
// 跨域预检请求
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// web jars
.antMatchers("/webjars/**").permitAll()
// 查看SQL监控(druid)
.antMatchers("/druid/**").permitAll()
// 首页和登录页面
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
// swagger
.antMatchers("/swagger-ui.html").permitAll()
.antMatchers("/swagger-resources/**").permitAll()
.antMatchers("/v2/api-docs").permitAll()
.antMatchers("/webjars/springfox-swagger-ui/**").permitAll()
// 验证码
.antMatchers("/captcha.jpg**").permitAll()
// 服务监控
.antMatchers("/actuator/**").permitAll()
// 其他所有请求需要身份认证
.anyRequest().authenticated();
// 退出登录处理器
http.logout().logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());
// token验证过滤器
http.addFilterBefore(new JwtAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
}
 
 
登录认证过滤器负责登录认证时检查并生产令牌保存到上下文,接口权限认证过程时,系统从上下文获取令牌校验接口访问权限,新建一个security包,在其下创建JwtAuthenticationFilter并继承BasicAuthenticationFilter,覆写其中的doFilterInternal方法进行Token校验。
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {
 
 
@Autowired
public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
 
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
// 获取token, 并检查登录状态
SecurityUtils.checkAuthentication(request);
chain.doFilter(request, response);
}
把验证逻辑抽取到了SecurityUtils的checkAuthentication方法中,checkAuthentication通过JwtTokenUtils的方法获取认证信息并保存到Spring Security上下文。
 

Spring Security

标签:repos   sse   basic   autowire   pass   页面   check   ons   VID   

原文地址:https://www.cnblogs.com/majianjun2131/p/14316080.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!