Spring Security 新版本配置
Springsecurity最新版配置
·
新版SpringSecurity配置
WebSecurityConfigurerAdapter 已经被废弃了,所以赶紧去看别人是如何写的,但是看到最后都没有看到特别好的博客,我就自己写了一下,可能写的不太好,希望大家可以积极讨论!
1、导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、配置文件
package com.sky.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
/**
* @author 尹稳健~
* @version 1.0
*/
@Configuration
public class SecurityConfig {
/**
* 加密方式
*
* @return
*/
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* 认证管理器,登录的时候参数会传给 authenticationManager
*
* @return
* @throws Exception
*/
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
/**
* 直接在过滤器链里面配置httpSecurity
*
* @param http
* @return
* @throws Exception
*/
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
//关闭csrf
.csrf().disable()
//不通过Session获取SecurityContext
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
// 允许跨域
.cors()
.and()
// 配置路劲是否需要认证
.authorizeRequests()
// 对于登录接口 允许匿名访问
.antMatchers("/user/login").permitAll()
// 配置权限
.antMatchers("/hello2").hasAuthority("/hello2")
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated()
.and()
.build();
}
}
3、编写service
@Service
public class LoginServiceImpl implements LoginService {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private RedisCache redisCache;
@Override
public ResponseResult login(User user) {
// AuthenticationManager的authenticate 进行用户认证
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
Authentication authenticate = authenticationManager.authenticate(authenticationToken);
// 如果认证没通过,提示
if (Objects.isNull(authenticate)){
throw new RuntimeException("用户名或密码错误!");
}
// 认证通过返回jwt
LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
System.out.println(loginUser);
Long userId = loginUser.getUser().getId();
String jwt = JwtUtil.createJWT(userId.toString());
Map<String, Object> map = new HashMap<>();
map.put("token",jwt);
// 将jwt存入redis中
redisCache.setCacheObject("login:"+userId,loginUser,5, TimeUnit.MINUTES);
return new ResponseResult(200,"登录成功!",map);
}
}
4、重写UserDetailsService
package com.sky.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.domain.LoginUser;
import com.sky.domain.User;
import com.sky.mapper.MenuMapper;
import com.sky.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author 尹稳健~
* @version 1.0
*/
@Service
public class UserServiceImpl implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Autowired
private MenuMapper menuMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 查询用户信息
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getUserName,username);
User user = userMapper.selectOne(queryWrapper);
// 如果没有查询到用户
if (user == null){
throw new RuntimeException("用户名错误或者密码错误");
}
return new LoginUser(user);
}
}
更多推荐
已为社区贡献3条内容
所有评论(0)