提前打開Redis
1)通過內置的用戶名和密碼登錄
spring-boot-starter-security.jar
2)使用自定義用戶名和密碼登錄
UserDetailService
自定義類實現UserDetailService接口,重寫loadUserByUsername方法
class UserDetailServiceImpl implements UserDetailService{public UserDetails loadUserByUsername(String username){//查詢數據庫表//獲取用戶信息SysUser user = mapper.方法();//封裝到UserDetails對象中LoginUser loginUser = new LoginUser(user);}}
?
class LoginUser implements UserDetails{private SysUser sysUser;public LoginUser(SysUser user){this.sysUser = user;}getUsername(){return "用戶名"}getPassword(){}get....
}
3)加密功能 bcryptPasswordEncoder
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {/*創建加密對象(密碼匹配器對象)*/@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}
4)自定義登錄接口
@RestController
public class LoginController {@Autowiredprivate LoginService loginService;@RequestMapping("/login")public R login(String username, String password) throws AuthenticationException {//調用servicereturn loginService.login(username, password);}
}
@Service
public class LoginServiceImpl implements LoginService {@Autowiredprivate AuthenticationManager authenticationManager;@Overridepublic R login(String username, String password) throws AuthenticationException {UsernamePasswordAuthenticationToken token =new UsernamePasswordAuthenticationToken(username, password);//調用認證提供器的認證方法,進行用戶名,密碼認證Authentication authentication = authenticationManager.authenticate(token);//根據返回值判斷是否認證成功if(authentication.isAuthenticated()){//認證成功//獲取用戶身份 LoginUserLoginUser user = (LoginUser) authentication.getPrincipal();//獲取用戶idLong id = user.getSysUser().getId();//根據用戶id,生成tokenString token2 = JwtUtil.createJWT(id+"");//返回 code ,msg,tokenreturn R.ok(token2,"認證成功");}return null;}
}
5)登錄成功后緩存用戶信息到redis
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
//將用戶信息存儲到redis中
redisTemplate.opsForValue().set(id,user,30, TimeUnit.MINUTES);
//將用戶信息存儲到SecurityContext上下文環境中,供其他過濾器使用
SecurityContextHolder.getContext().setAuthentication(authentication);
完整代碼如下:
package com.hl.springsecurity01.service.impl;
?
import com.hl.springsecurity01.domain.R;
import com.hl.springsecurity01.security.LoginUser;
import com.hl.springsecurity01.service.LoginService;
import com.hl.springsecurity01.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
?
import javax.security.sasl.AuthenticationException;
import java.util.concurrent.TimeUnit;
?
@Service
public class LoginServiceImpl implements LoginService {@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate RedisTemplate redisTemplate;@Overridepublic R login(String username, String password) throws AuthenticationException {UsernamePasswordAuthenticationToken token =new UsernamePasswordAuthenticationToken(username, password);//調用認證提供器的認證方法,進行用戶名,密碼認證Authentication authentication = authenticationManager.authenticate(token);//根據返回值判斷是否認證成功if(authentication == null){//認證失敗throw ?new AuthenticationException("用戶名或者密碼錯誤");}if(authentication.isAuthenticated()){//認證成功//獲取用戶身份 LoginUserLoginUser user = (LoginUser) authentication.getPrincipal();//獲取用戶idLong id = user.getSysUser().getId();//將用戶信息存儲到redis中redisTemplate.opsForValue().set(id,user,30, TimeUnit.MINUTES);//將用戶信息存儲到SecurityContext上下文環境中,供其他過濾器使用SecurityContextHolder.getContext().setAuthentication(authentication);//根據用戶id,生成tokenString token2 = JwtUtil.createJWT(id+"");//返回 code ,msg,tokenreturn R.ok(token2,"認證成功");}return null;}
}
6)攜帶token,訪問目標方法
創建過濾器并配置過濾器
/*
創建token過濾器*/
@Component
public class JWTAuthenticationTokenFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain) throws ServletException, IOException {System.out.println("到達jwt過濾器.....");//放行,到達目標方法filterChain.doFilter(request,response);}
}
package com.hl.springsecurity01.security;
?
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate JWTAuthenticationTokenFilter authenticationTokenFilter;/*創建加密對象(密碼匹配器對象)*/@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()// 對于登錄接口 允許匿名訪問.antMatchers("/login").anonymous()// 除上面外的所有請求全部需要鑒權認證.anyRequest().authenticated();
?//配置自定義過濾器http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);}@Beanpublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}
}
token過濾器完整代碼
package com.hl.springsecurity01.security;
?
import com.hl.springsecurity01.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
?
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
創建token過濾器*/
@Component
public class JWTAuthenticationTokenFilter extends OncePerRequestFilter {@Autowiredprivate RedisTemplate redisTemplate;@Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain) throws ServletException, IOException {System.out.println("到達jwt過濾器.....");//獲取請求頭中的tokenString token = request.getHeader("token");if(token == null){
// ? ? ? ? ? throw new RuntimeException("token不能為空!");System.out.println("token為空!");//放行,到usernamePasswordtokenfilterChain.doFilter(request,response);return;}//校驗token是否合法Long userId = null;try {Claims claims = JwtUtil.parseJWT(token);userId = Long.parseLong(claims.getSubject());} catch (Exception e) {e.printStackTrace();throw ?new RuntimeException("token 不合法");}//判斷用戶是否登錄成功,服務端是否存在該用戶信息Object obj = redisTemplate.opsForValue().get(userId);if(obj == null){System.out.println("用戶未登錄");throw new RuntimeException("用戶未登錄!");}//將登錄成功的用戶信息設置到SecurityContext中UsernamePasswordAuthenticationToken authenticationToken =new UsernamePasswordAuthenticationToken(obj,null,null);SecurityContextHolder.getContext().setAuthentication(authenticationToken);
?
?//放行,到達目標方法filterChain.doFilter(request,response);}
}
7)退出登錄
package com.hl.springsecurity01.web;
?
import com.hl.springsecurity01.domain.R;
import com.hl.springsecurity01.service.LoginService;
import com.hl.springsecurity01.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
?
import javax.security.sasl.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
?
@RestController
public class LoginController {@Autowiredprivate LoginService loginService;@Autowiredprivate RedisTemplate redisTemplate;@RequestMapping("/login")public R login(String username, String password) throws AuthenticationException {//調用servicereturn loginService.login(username, password);}@RequestMapping("/logout1")public R logout(HttpServletRequest request) throws Exception {String token = request.getHeader("token");//解析token,得到用戶idClaims claims = JwtUtil.parseJWT(token);Object object = claims.getSubject();Long userId = Long.parseLong(object.toString());//從redis中刪除用戶信息redisTemplate.delete(userId);//springsecurity上下文中清除用戶信息SecurityContextHolder.getContext().setAuthentication(null);return R.ok();}
?
}
8)權限控制
1. 開啟權限攔截
@SpringBootApplication
@MapperScan(basePackages = "com.hl.springsecurity01.mapper")
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class Springsecurity01Application {
?public static void main(String[] args) {SpringApplication.run(Springsecurity01Application.class, args);}
?
}
2.方法上添加攔截注解
@Controller
public class BasicController {
?// http://127.0.0.1:8080/hello?name=lisi@RequestMapping("/hello")@PreAuthorize("hasAuthority('user:list')")@ResponseBodypublic String hello(@RequestParam(name = "name", defaultValue = "unknown user") String name) {return "Hello " + name;}
3、授權(模擬字符串授權)
UserDetailsService和UserDetails
/*
根據用戶名查找用戶對象*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {//根據用戶名,到數據庫表中,查找用戶對象QueryWrapper queryWrapper = new QueryWrapper();queryWrapper.eq("user_name", username);List<SysUser> list = sysUserService.list(queryWrapper);//判斷用戶是否存在LoginUser user = null;if(list != null && list.size() > 0){SysUser sysUser = list.get(0);//授權List<String> permissions = new ArrayList<>();permissions.add("user:list");permissions.add("user:add");//封裝數據到UserDetails接口實現類對象中user = new LoginUser(sysUser,permissions);}return user;
}
@Data
public class LoginUser implements UserDetails {
?private SysUser sysUser;private List<String> permissions;
?public LoginUser() {}public LoginUser(SysUser sysUser, List<String> permissions) {this.sysUser = sysUser;this.permissions = permissions;}
?//返回用戶權限信息,返回權限列表@Overridepublic Collection<? extends GrantedAuthority> getAuthorities() {List<GrantedAuthority> list = new ArrayList<>();for (String permission : permissions) {list.add(new SimpleGrantedAuthority(permission));}return list;}
JwtAuthenticationInterceptor
package com.hl.springsecurity01.security;
?
import com.hl.springsecurity01.util.JwtUtil;
import com.mysql.cj.log.Log;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
?
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
創建token過濾器*/
@Component
public class JWTAuthenticationTokenFilter extends OncePerRequestFilter {@Autowiredprivate RedisTemplate redisTemplate;@Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain) throws ServletException, IOException {System.out.println("到達jwt過濾器.....");//獲取請求頭中的tokenString token = request.getHeader("token");if(token == null){
// ? ? ? ? ? throw new RuntimeException("token不能為空!");System.out.println("token為空!");//放行,到usernamePasswordtokenfilterChain.doFilter(request,response);return;}//校驗token是否合法Long userId = null;try {Claims claims = JwtUtil.parseJWT(token);userId = Long.parseLong(claims.getSubject());} catch (Exception e) {e.printStackTrace();throw ?new RuntimeException("token 不合法");}//判斷用戶是否登錄成功,服務端是否存在該用戶信息Object obj = redisTemplate.opsForValue().get(userId);if(obj == null){System.out.println("用戶未登錄");throw new RuntimeException("用戶未登錄!");}LoginUser user = (LoginUser)obj;//將登錄成功的用戶信息設置到SecurityContext中UsernamePasswordAuthenticationToken authenticationToken =new UsernamePasswordAuthenticationToken(obj,null,user.getAuthorities());SecurityContextHolder.getContext().setAuthentication(authenticationToken);
?
?//放行,到達目標方法filterChain.doFilter(request,response);}
}
/*** @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>*/
@Controller
public class BasicController {
?// http://127.0.0.1:8080/hello?name=lisi@RequestMapping("/hello")@PreAuthorize("hasAuthority('user:list')")@ResponseBodypublic String hello(@RequestParam(name = "name", defaultValue = "unknown user") String name) {return "Hello " + name;}
?// http://127.0.0.1:8080/hello?name=lisi@RequestMapping("/hello2")@PreAuthorize("hasAuthority('user:hello')")@ResponseBodypublic String hello2(@RequestParam(name = "name", defaultValue = "unknown user") String name) {return "Hello " + name;}
hello可以訪問,hello2無法訪問。
4、授權(連接數據庫表)
public interface SysUserMapper extends BaseMapper<SysUser> {
?@Select(value = "select sys_menu.perms " +"from sys_menu " +"join sys_role_menu on sys_menu.menu_id = sys_role_menu.menu_id " +"join sys_user_role on sys_role_menu.role_id = sys_user_role.role_id " +"where sys_user_role.user_id = #{id} and perms is not null and perms !=''")public List<String> findPermissionsByUserId(Long userId);
}
package com.hl.springsecurity01.security;
?
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hl.springsecurity01.domain.SysUser;
import com.hl.springsecurity01.service.SysUserService;
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.ArrayList;
import java.util.List;
?
@Service
public class UserDetailsServiceImpl implements UserDetailsService {@Autowiredprivate SysUserService sysUserService;/*根據用戶名查找用戶對象*/@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {//根據用戶名,到數據庫表中,查找用戶對象QueryWrapper queryWrapper = new QueryWrapper();queryWrapper.eq("user_name", username);List<SysUser> list = sysUserService.list(queryWrapper);//判斷用戶是否存在LoginUser user = null;if(list != null && list.size() > 0){SysUser sysUser = list.get(0);//授權
// ? ? ? ? ? List<String> permissions = new ArrayList<>();
// ? ? ? ? ? permissions.add("user:list");
// ? ? ? ? ? permissions.add("user:add");List<String> permissions = sysUserService.findPermissionsByUserId(sysUser.getId());//封裝數據到UserDetails接口實現類對象中user = new LoginUser(sysUser,permissions);}return user;}
}
9)權限控制相關的注解
在Spring Security中,hasRole和hasAuthority都可以用來控制用戶的訪問權限,但它們有一些細微的差別。
hasRole方法是基于角色進行訪問控制的。它檢查用戶是否有指定的角色,并且這些角色以"ROLE_"前綴作為前綴(例如"ROLE_ADMIN")。
hasAuthority方法是基于權限進行訪問控制的。它檢查用戶是否有指定的權限,并且這些權限沒有前綴。
因此,使用hasRole方法需要在用戶的角色名稱前添加"ROLE_"前綴,而使用hasAuthority方法不需要這樣做。
例如,假設用戶有一個角色為"ADMIN"和一個權限為"VIEW_REPORTS",可以使用以下方式控制用戶對頁面的訪問權限:
.antMatchers("/admin/").hasRole("ADMIN") .antMatchers("/reports/").hasAuthority("VIEW_REPORTS") 在這個例子中,只有具有"ROLE_ADMIN"角色的用戶才能訪問/admin/路徑下的頁面,而具有"VIEW_REPORTS"權限的用戶才能訪問/reports/路徑下的頁面。
@PreAuthorize("hasAuthority('system:user:list')") ? 特定的菜單權限
@PreAuthorize("hasAnyAuthority('system:user:list','system:user:add')") 多個菜單權限只要有一個就可以訪問
@PreAuthorize("hasRole('admin')")
@PreAuthorize("hasAnyRole('admin','comm')")-- 根據用戶,查詢角色列表
select sys_role.role_key
from sys_role join sys_user_role
on sys_role.role_id = sys_user_role.role_id
where sys_user_role.user_id = 2
union all
select sys_menu.perms
from sys_menu
join sys_role_menu on sys_menu.menu_id = sys_role_menu.menu_id
join sys_user_role on sys_role_menu.role_id = sys_user_role.role_id
where sys_user_role.user_id = 2 and perms is not null and perms !=''
?
?
?
ROLE_common
system:user:list
system:role:list
system:menu:list
system:dept:list
system:post:list