srpingboot这里就不再进行赘述,相信大家都非常的熟悉了
Shiro
一个安全框架,可以实现用户的认证和授权。比SpringSecurity要简单的多。
Jwt
我的理解就是可以进行客户端与服务端之间验证的一种技术,取代了之前使用 Session 来验证的不安全性
什么不适用 Session?
原理是,登录之后客户端和服务端各自保存一个相应的 SessionId,每次客户端发起请求的时候就得携带这个 SessionId 来进行比对 1、Session 在用户请求量大的时候服务器开销太大了 2、Session 不利于搭建服务器的集群(也就是必须访问原本的那个服务器才能获取对应的 SessionId) 它使用的是一种令牌技术
Jwt 字符串分为三部分
Header
存储两个变量
1、秘钥(可以用来比对)
2、算法(也就是下面将 Header 和 payload 加密成 Signature)
payload
存储很多东西,基础信息有如下几个
1、签发人,也就是这个 “令牌” 归属于哪个用户。一般是userId
2、创建时间,也就是这个令牌是什么时候创建的
3、失效时间,也就是这个令牌什么时候失效
4、唯一标识,一般可以使用算法生成一个唯一标识
Signature
这个是上面两个经过 Header 中的算法加密生成的,用于比对信息,防止篡改 Header 和 payload
然后将这三个部分的信息经过加密生成一个JwtToken的字符串,发送给客户端,客户端保存在本地。当客户端发起请求的时候携带这个到服务端 (可以是在cookie,可以是在header,可以是在localStorage中),在服务端进行验证
springboot+shiro+jwt
pom.xml
由于需要对 shiro 的 SecurityManager 进行设置,所以不能使用 shiro-spring-boot-starter 进行与 springboot 的整合,只能使用 spring-shiro
<!--项目中org.apache.commons.codec.binary.Base64所需-->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<!--java-jwt-核心依赖-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.11.0</version>
</dependency>
<!--jjwt-java版本的辅助帮助模块-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<!--shiro相关依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
springboot和shiro的整合
创建 ShiroConfig.java 进行一些简单的配置
@Configuration
@Slf4j
public class ShiroConfig {
@Bean
public Realm customRealm() {
return new CustomRealm();
}
@Bean
public DefaultWebSecurityManager securityManager(Realm customRealm,SubjectFactory subjectFactory) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(customRealm);
return securityManager;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
log.info("进入shiro拦截器");
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
shiroFilter.setSecurityManager(securityManager);
shiroFilter.setLoginUrl("/unauthenticated");
shiroFilter.setUnauthorizedUrl("/unauthorized");
Map<String, String> filterRuleMap = new LinkedHashMap<>();
filterRuleMap.put("/login", "anon");
filterRuleMap.put("/logout", "logout");
shiroFilter.setFilterChainDefinitionMap(filterRuleMap);
return shiroFilter;
}
}
创建自定义的 Realm
@Slf4j
public class CustomRealm extends AuthorizingRealm {
private static final Set<String> tomRoleNameSet = new HashSet<>();
private static final Set<String> tomPermissionNameSet = new HashSet<>();
private static final Set<String> jerryRoleNameSet = new HashSet<>();
private static final Set<String> jerryPermissionNameSet = new HashSet<>();
static {
tomRoleNameSet.add("admin");
jerryRoleNameSet.add("user");
tomPermissionNameSet.add("user:insert");
tomPermissionNameSet.add("user:update");
tomPermissionNameSet.add("user:delete");
tomPermissionNameSet.add("user:query");
jerryPermissionNameSet.add("user:query");
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
log.info("开始进行授权===》{}", principals.getPrimaryPrincipal());
String userName = (String) principals.getPrimaryPrincipal();
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
if (userName.equals("tom")) {
authorizationInfo.addRoles(tomRoleNameSet);
authorizationInfo.addStringPermissions(tomPermissionNameSet);
}
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userName = (String) token.getPrincipal();
if (userName.equals("tom")) {
return new SimpleAuthenticationInfo(userName, "123456", this.getName());
}
return null;
}
}
SpringBoot 整合 Jwt
创建 JwtUtil
public class JwtUtil {
private final String base64EncodedSecretKey;
private final SignatureAlgorithm signatureAlgorithm;
public JwtUtil(String secretKey, SignatureAlgorithm signatureAlgorithm) {
this.base64EncodedSecretKey = Base64.encodeBase64String(secretKey.getBytes());
this.signatureAlgorithm = signatureAlgorithm;
}
public String encode(String iss, long ttlMillis, Map<String, Object> claims) {
if (claims == null) {
claims = new HashMap<>();
}
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
JwtBuilder builder = Jwts.builder()
.setClaims(claims)
.setId(UUID.randomUUID().toString())
.setIssuedAt(now)
.setSubject(iss)
.signWith(signatureAlgorithm, base64EncodedSecretKey);
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
return builder.compact();
}
public Claims decode(String jwtToken) {
return Jwts.parser()
.setSigningKey(base64EncodedSecretKey)
.parseClaimsJws(jwtToken)
.getBody();
}
public boolean isVerify(String jwtToken) {
Algorithm algorithm = null;
switch (signatureAlgorithm) {
case HS256:
algorithm = Algorithm.HMAC256(Base64.decodeBase64(base64EncodedSecretKey));
break;
default:
throw new RuntimeException("不支持该算法");
}
JWTVerifier verifier = JWT.require(algorithm).build();
verifier.verify(jwtToken);
return true;
}
public static void main(String[] args) {
JwtUtil util = new JwtUtil("tom", SignatureAlgorithm.HS256);
Map<String, Object> map = new HashMap<>();
map.put("username", "tom");
map.put("password", "123456");
map.put("age", 20);
String jwtToken = util.encode("tom", 30000, map);
System.out.println(jwtToken);
util.decode(jwtToken).entrySet().forEach((entry) -> {
System.out.println(entry.getKey() + ": " + entry.getValue());
});
}
}
springboot+shiro+jwt
由于需要对 shiro 的 SecurityManager 进行设置,所以不能使用 shiro-spring-boot-starter 进行与 springboot 的整合,只能使用 spring-shiro
<!-- 自动依赖导入 shiro-core 和 shiro-web -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
JwtDeafultSubjectFactory
由于需要实现无状态的 web,所以使用不到 Shiro 的 Session 功能,严谨点就是将其关闭
public class JwtDefaultSubjectFactory extends DefaultWebSubjectFactory{
@Override
public Subject createSubject(SubjectContext context) {
context.setSessionCreationEnabled(false);
return super.createSubject(context);
}
}
创建 JwtUtil
@Component
public class JwtUtil {
private static final String defaultbase64EncodedSecretKey = "badbabe";
private static final SignatureAlgorithm defaultsignatureAlgorithm = SignatureAlgorithm.HS256;
public JwtUtil() {
this(defaultbase64EncodedSecretKey, defaultsignatureAlgorithm);
}
private final String base64EncodedSecretKey;
private final SignatureAlgorithm signatureAlgorithm;
public JwtUtil(String secretKey, SignatureAlgorithm signatureAlgorithm) {
this.base64EncodedSecretKey = Base64.encodeBase64String(secretKey.getBytes());
this.signatureAlgorithm = signatureAlgorithm;
}
public String encode(String iss, long ttlMillis, Map<String, Object> claims) {
if (claims == null) {
claims = new HashMap<>();
}
long nowMillis = System.currentTimeMillis();
JwtBuilder builder = Jwts.builder()
.setClaims(claims)
.setId(UUID.randomUUID().toString())
.setIssuedAt(new Date(nowMillis))
.setSubject(iss)
.signWith(signatureAlgorithm, base64EncodedSecretKey);
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
return builder.compact();
}
public Claims decode(String jwtToken) {
return Jwts.parser()
.setSigningKey(base64EncodedSecretKey)
.parseClaimsJws(jwtToken)
.getBody();
}
public boolean isVerify(String jwtToken) {
Algorithm algorithm = null;
switch (signatureAlgorithm) {
case HS256:
algorithm = Algorithm.HMAC256(Base64.decodeBase64(base64EncodedSecretKey));
break;
default:
throw new RuntimeException("不支持该算法");
}
JWTVerifier verifier = JWT.require(algorithm).build();
verifier.verify(jwtToken);
return true;
}
public static void main(String[] args) {
JwtUtil util = new JwtUtil("tom", SignatureAlgorithm.HS256);
Map<String, Object> map = new HashMap<>();
map.put("username", "tom");
map.put("password", "123456");
map.put("age", 20);
String jwtToken = util.encode("tom", 30000, map);
System.out.println(jwtToken);
util.decode(jwtToken).entrySet().forEach((entry) -> {
System.out.println(entry.getKey() + ": " + entry.getValue());
});
}
}
创建 JwtFilter
在 Shiro 的拦截器中多加一个,等下需要在配置文件中注册这个过滤器
@Configuration
@Slf4j
public class ShiroConfig {
@Bean
public SubjectFactory subjectFactory() {
return new JwtDefaultSubjectFactory();
}
@Bean
public Realm customRealm() {
return new CustomRealm();
}
@Bean
public DefaultWebSecurityManager securityManager(Realm customRealm,SubjectFactory subjectFactory) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(customRealm);
DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
securityManager.setSubjectDAO(subjectDAO);
securityManager.setSubjectFactory(subjectFactory);
return securityManager;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
log.info("进入shiro拦截器");
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
shiroFilter.setSecurityManager(securityManager);
shiroFilter.setLoginUrl("/unauthenticated");
shiroFilter.setUnauthorizedUrl("/unauthorized");
Map<String, Filter> filterMap = new HashMap<>();
filterMap.put("anon", new AnonymousFilter());
filterMap.put("jwt", new JwtFilter());
filterMap.put("logout", new LogoutFilter());
shiroFilter.setFilters(filterMap);
Map<String, String> filterRuleMap = new LinkedHashMap<>();
filterRuleMap.put("/login", "anon");
filterRuleMap.put("/logout", "logout");
filterRuleMap.put("/swagger-ui.html", "anon");
filterRuleMap.put("/swagger-resources", "anon");
filterRuleMap.put("/v2/api-docs", "anon");
filterRuleMap.put("/webjars/springfox-swagger-ui/**", "anon");
filterRuleMap.put("/configuration/security", "anon");
filterRuleMap.put("/configuration/ui", "anon");
filterRuleMap.put("/**", "jwt");
shiroFilter.setFilterChainDefinitionMap(filterRuleMap);
return shiroFilter;
}
}
创建 JwtToken
用于在customRealm中用token获取Principal
public class JwtToken implements AuthenticationToken {
private String jwt;
public JwtToken(String jwt) {
this.jwt = jwt;
}
@Override
public Object getPrincipal() {
return jwt;
}
@Override
public Object getCredentials() {
return jwt;
}
}
JwtRealm
创建判断jwt是否有效的认证方式的Realm
@Slf4j
public class JwtRealm extends AuthorizingRealm {
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof JwtToken;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String jwt = (String) token.getPrincipal();
if (jwt == null) {
throw new NullPointerException("jwtToken 不允许为空");
}
JwtUtil jwtUtil = new JwtUtil();
if (!jwtUtil.isVerify(jwt)) {
throw new UnknownAccountException();
}
String username = (String) jwtUtil.decode(jwt).get("username");
log.info("在使用token登录"+username);
return new SimpleAuthenticationInfo(jwt,jwt,"JwtRealm");
}
}
ShiroConfig
配置信息
1、因为不适用 Session,所以为了防止会调用 getSession() 方法而产生错误,所以默认调用自定义的 Subject 方法 2、一些修改,关闭 SHiroDao 等 3、注册 JwtFilter
@Configuration
@Slf4j
public class ShiroConfig {
@Bean
public SubjectFactory subjectFactory() {
return new JwtDefaultSubjectFactory();
}
@Bean
public Realm customRealm() {
return new CustomRealm();
}
@Bean
public DefaultWebSecurityManager securityManager(Realm customRealm,SubjectFactory subjectFactory) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(customRealm);
DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
securityManager.setSubjectDAO(subjectDAO);
securityManager.setSubjectFactory(subjectFactory);
return securityManager;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
log.info("进入shiro拦截器");
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
shiroFilter.setSecurityManager(securityManager);
shiroFilter.setLoginUrl("/unauthenticated");
shiroFilter.setUnauthorizedUrl("/unauthorized");
Map<String, Filter> filterMap = new HashMap<>();
filterMap.put("anon", new AnonymousFilter());
filterMap.put("jwt", new JwtFilter());
filterMap.put("logout", new LogoutFilter());
shiroFilter.setFilters(filterMap);
Map<String, String> filterRuleMap = new LinkedHashMap<>();
filterRuleMap.put("/login", "anon");
filterRuleMap.put("/logout", "logout");
filterRuleMap.put("/swagger-ui.html", "anon");
filterRuleMap.put("/swagger-resources", "anon");
filterRuleMap.put("/v2/api-docs", "anon");
filterRuleMap.put("/webjars/springfox-swagger-ui/**", "anon");
filterRuleMap.put("/configuration/security", "anon");
filterRuleMap.put("/configuration/ui", "anon");
filterRuleMap.put("/**", "jwt");
shiroFilter.setFilterChainDefinitionMap(filterRuleMap);
return shiroFilter;
}
}
测试
@Slf4j
@Controller
public class LoginController {
@RequestMapping("/login")
public ResponseEntity<Map<String, String>> login(String username, String password) {
log.info("username:{},password:{}", username, password);
Map<String, String> map = new HashMap<>();
if (!"tom".equals(username) || !"123".equals(password)) {
map.put("msg", "用户名密码错误");
return ResponseEntity.ok(map);
}
JwtUtil jwtUtil = new JwtUtil();
Map<String, Object> chaim = new HashMap<>();
chaim.put("username", username);
chaim.put("password",password);
String jwtToken = jwtUtil.encode(username, 100 * 60 * 1000, chaim);
map.put("msg", "登录成功");
map.put("token", jwtToken);
return ResponseEntity.ok(map);
}
@RequestMapping("/logout")
public ResponseEntity<String> logout(){
return ResponseEntity.ok("退出成功");
}
@RequestMapping("/testdemo")
public ResponseEntity<String> testdemo() {
return ResponseEntity.ok("你好吗");
}
}
|