盘点认证框架 简单过一下 Shiro

总文档 :文章目录

Github : github.com/black-ant

一 . 前言

之前说了 SpringSecurity , 也说了 Pac4j , 后续准备把 Shiro 和 CAS 也完善进来 , Shiro 整个框架结构比较简单 , 这一篇也只是简单过一下 , 不深入太多.

1.1 基础知识

Shiro 的基础知识推荐看官方文档 Shiro Doc , 这里就简单的罗列一下

Shiro 具有很简单的体系结构 (Subject,SecurityManager 和 Realms) , 按照流程大概就是这样

1
2
3
4
5
java复制代码ApplicationCode -->  Subject (Current User)
|
SecurityManager (Managers all Subject)
|
Realms

Shiro 的基石

Shiro 自己内部定义了4个功能基石 , 分为身份验证、授权、会话管理和密码学

  • Authentication : 身份认证 , 证明用户身份的行为
  • Authorization : 访问控制的过程,即确定谁可以访问什么
  • Session Management : 管理特定于用户的会话,即使是在非 web 或 EJB 应用程序中
  • Cryptography : 使用加密算法来保证数据的安全,同时仍然易于使用

image.png

image.png

以及一些额外的功能点:

  • Web Support : Shiro 的 Web 支持 api 帮助简单地保护 Web 应用程序
  • Caching : 缓存是 Apache Shiro API 中的第一层,用于确保安全操作保持快速和高效
  • Concurrency : Apache Shiro 支持多线程应用程序及其并发特性
  • Run As : 允许用户假设另一个用户的身份的特性 (我理解这就是代办)
  • Remember Me : 记住我功能

补充隐藏概念:

  • Permission : 许可
  • Role : 角色

二 . 基本使用

Shiro 的使用对我而言第一感觉就是干净 , 你不需要像 SpringSecurity 一样去关注很多配置 ,关注很多Filter , 也不需要像 CAS 源码一样走了很多 WebFlow , 所有的认证都是由你自己去完成的.

2.1 配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
java复制代码@Configuration
public class shiroConfig {


/**
* 配置 Realm
*
* @return
*/
@Bean
public CustomRealm myShiroRealm() {
CustomRealm customRealm = new CustomRealm();
return customRealm;
}

/**
* 权限管理,配置主要是Realm的管理认证
* @return
*/
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
return securityManager;
}

//Filter工厂,设置对应的过滤条件和跳转条件
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, String> map = new HashMap<>();
// logout url
map.put("/logout", "logout");
//对所有用户认证
map.put("/**", "authc");
//登录
shiroFilterFactoryBean.setLoginUrl("/login");
//首页
shiroFilterFactoryBean.setSuccessUrl("/index");
//错误页面,认证不通过跳转
shiroFilterFactoryBean.setUnauthorizedUrl("/error");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}

/**
* 注册 SecurityManager
*
* @param securityManager
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}


/**
* AOP 注解冲突解决方式
*
* @return
*/
@Bean
@ConditionalOnMissingBean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
defaultAAP.setProxyTargetClass(true);
return defaultAAP;
}
}

2.2 发起认证

Shiro 发起认证很简答 , 完全是手动发起

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
java复制代码     Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
user.getUserName(),
user.getPassword()
);
try {
//进行验证,这里可以捕获异常,然后返回对应信息
subject.login(usernamePasswordToken);
// subject.checkRole("admin");
// subject.checkPermissions("query", "add");
} catch (UnknownAccountException e) {
log.error("用户名不存在!", e);
return "用户名不存在!";
} catch (AuthenticationException e) {
log.error("账号或密码错误!", e);
return "账号或密码错误!";
} catch (AuthorizationException e) {
log.error("没有权限!", e);
return "没有权限";
}

因为是完全手动发起的 , 所以在集成 Shiro 的时候毫无压力 , 可以自行在外层封装任何的接口 , 也可以在接口中做任何的事情.

2.3 校验逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
java复制代码public class CustomRealm extends AuthorizingRealm {

@Autowired
private LoginService loginService;

/**
* @MethodName doGetAuthorizationInfo
* @Description 权限配置类
* @Param [principalCollection]
* @Return AuthorizationInfo
* @Author WangShiLin
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//获取登录用户名
String name = (String) principalCollection.getPrimaryPrincipal();
//查询用户名称
User user = loginService.getUserByName(name);
//添加角色和权限
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
for (Role role : user.getRoles()) {
//添加角色
simpleAuthorizationInfo.addRole(role.getRoleName());
//添加权限
for (Permissions permissions : role.getPermissions()) {
simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
}
}
return simpleAuthorizationInfo;
}

/**
* @MethodName doGetAuthenticationInfo
* @Description 认证配置类
* @Param [authenticationToken]
* @Return AuthenticationInfo
* @Author WangShiLin
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
if (StringUtils.isEmpty(authenticationToken.getPrincipal())) {
return null;
}
//获取用户信息
String name = authenticationToken.getPrincipal().toString();
User user = loginService.getUserByName(name);
if (user == null) {
//这里返回后会报出对应异常
return null;
} else {
//这里验证authenticationToken和simpleAuthenticationInfo的信息
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, user.getPassword().toString(), getName());
return simpleAuthenticationInfo;
}
}
}

LoginServiceImpl 也简单贴一下 , 就是从数据源中获取用户而已

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
java复制代码@Service
public class LoginServiceImpl implements LoginService {

@Autowired
private PermissionServiceImpl permissionService;

@Override
public User getUserByName(String getMapByName) {
return getMapByName(getMapByName);
}

/**
* 模拟数据库查询
*
* @param userName 用户名
* @return User
*/
private User getMapByName(String userName) {

// 构建 Role 1
Role role = new Role("1", "admin", getAllPermission());
Set<Role> roleSet = new HashSet<>();
roleSet.add(role);

// 构建 Role 2
Role role1 = new Role("2", "user", getSinglePermission());
Set<Role> roleSet1 = new HashSet<>();
roleSet1.add(role1);

User user = new User("1", "root", "123456", roleSet);
Map<String, User> map = new HashMap<>();
map.put(user.getUserName(), user);

User user1 = new User("2", "zhangsan", "123456", roleSet1);
map.put(user1.getUserName(), user1);

return map.get(userName);
}

/**
* 权限类型一
*/
private Set<Permissions> getAllPermission() {
Set<Permissions> permissionsSet = new HashSet<>();
permissionsSet.add(permissionService.getPermsByUserId("1"));
permissionsSet.add(permissionService.getPermsByUserId("2"));
return permissionsSet;
}

/**
* 权限类型二
*/
private Set<Permissions> getSinglePermission() {
Set<Permissions> permissionsSet1 = new HashSet<>();
permissionsSet1.add(permissionService.getPermsByUserId("1"));
return permissionsSet1;
}

}

LoginServiceImpl其实都可以不算是 Shiro 整个认证体系的一员 ,它只是做一个 User 管理的业务而已 , 那么剩下了干了什么?

  • 写了一个 API 接口
  • 准备了一个 Realm
  • 通过 Subject 发起认证
  • 在接口上标注相关的注解

整套流程下来 , 就是简单 , 便捷 , 很轻松的就集成了认证的功能.

三 . 源码

按照惯例 , 还是看一遍源码吧 ,我们按照四个维度来分析 :

  • 请求的拦截
  • 请求的校验
  • 认证的过程
  • 退出的过程

3.1 请求的拦截

这要从 ShiroFilterFactoryBean 这个类开始

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
JAVA复制代码    @Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//....
//登录
shiroFilterFactoryBean.setLoginUrl("/login");
//首页
shiroFilterFactoryBean.setSuccessUrl("/index");
//错误页面,认证不通过跳转
shiroFilterFactoryBean.setUnauthorizedUrl("/error");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}


C- ShiroFilterFactoryBean
?- 构建 ShiroFilterFactoryBean 时会为其配置一个 login 地址
M- applyGlobalPropertiesIfNecessary : 配置全局属性
- applyLoginUrlIfNecessary(filter);
- applySuccessUrlIfNecessary(filter);
- applyUnauthorizedUrlIfNecessary(filter);

M- applyLoginUrlIfNecessary
?- 为 Filter 配置 loginUrl
- String existingLoginUrl = acFilter.getLoginUrl();
- acFilter.setLoginUrl(loginUrl)





// 这里对所有的 地址做了拦截
C01- PathMatchingFilter
F- protected Map<String, Object> appliedPaths = new LinkedHashMap<String, Object>();
?- 所有的path均会在这里处理
- 拦截成功了会调用 isFilterChainContinued , 最终会调用 onAccessDenied -> M2_01

C02- FormAuthenticationFilter
M2_01- onAccessDenied
-

// 判断是否需要重定向
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
if (isLoginRequest(request, response)) {
if (isLoginSubmission(request, response)) {
return executeLogin(request, response);
} else {
return true;
}
} else {
// 重定向到 login 页
saveRequestAndRedirectToLogin(request, response);
return false;
}
}

// 当然还有已登录得逻辑 , 已登录是在上面之前判断得
C- AccessControlFilter
M- onPreHandle
?- 该方法中会调用其他得 Filter 判断是否登录

// 例如这里就是 AuthenticationFilter 获取 Subject
C- AuthenticationFilter
M- isAccessAllowed
- Subject subject = getSubject(request, response);
- return subject.isAuthenticated() && subject.getPrincipal() != null;

整体的调用链大概是

  • OncePerRequestFilter # doFilter
  • AbstractShiroFilter # call
  • AbstractShiroFilter # executeChain
  • ProxiedFilterChain # doFilter
  • AdviceFilter # doFilterInternal
  • PathMatchingFilter # preHandle

最终会因为Filter 链 , 最终由 FormAuthenticationFilter 重定向出去

3.2 拦截的方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
java复制代码
按照我们的常规思路 , 拦截仍然是通过 Filter 来完成


C- AbstractShiroFilter
M- doFilterInternal
- final Subject subject = createSubject(request, response) : 通过 请求构建了一个 Subject
- 调用 Subject 的 Callable 回调
- updateSessionLastAccessTime(request, response);
- executeChain(request, response, chain);
M- executeChain
- 执行 FilterChain 判断
-

// 这里往上追溯 , 可以看到实际上是一个 AOP 操作 : ReflectiveMethodInvocation
// 再往上就是 AopAllianceAnnotationsAuthorizingMethodInterceptor , 注意这里面是懒加载的

C03- AnnotationsAuthorizingMethodInterceptor : 通过 Interceptor 对方法进行拦截
M3_01- assertAuthorized : 断言认证信息
- 获取一个集合 Collection<AuthorizingAnnotationMethodInterceptor>
FOR- 循环 AuthorizingAnnotationMethodInterceptor -> PS301
- assertAuthorized -> M3_05

C- AuthorizingAnnotationMethodInterceptor
M3_05- assertAuthorized(MethodInvocation mi)
- ((AuthorizingAnnotationHandler)getHandler()).assertAuthorized(getAnnotation(mi))
- 这里是获取 Method 上面的 Annotation , 再调用 assertAuthorized 验证 -> M5_01

// 补充 : PS301
TODO

C05- RoleAnnotationHandler
M5_01- assertAuthorized(Annotation a)
- 如果不是 RequiresRoles , 则直接返回
- getSubject().checkRole(roles[0]) -> M6_02
- getSubject().checkRoles(Arrays.asList(roles));
?- 注意 , 这里是区别 And 和 Or 将 roles 分别处理

请求的逻辑 :

M3_01M3_05M5_01M6_02M10_05M11_04M11_05
AuthorizingAnnotationMethodInterceptor.png

Shiro001.jpg

3.3 一个完整的认证过程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
java复制代码Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUserName(),user.getPassword());

subject.login(usernamePasswordToken);

// 来看一下 , 整个流程中做了什么
C06- DelegatingSubject
M6_01- login(AuthenticationToken token)
- Subject subject = securityManager.login(this, token) : 调用 securityManager 完成认证 :M8_01
M6_02- checkRole(String role)
- securityManager.checkRole(getPrincipals(), role) -> M10_04


C07- DefaultWebSecurityManager
M7_01-

C08- DefaultSecurityManager
M8_01- login(Subject subject, AuthenticationToken token)
- 底层调用 AuthorizingRealm 完成认证 , 此处的认证类为自定义的 CustomRealm

C09- AbstractAuthenticator
M9_01- authenticate(AuthenticationToken token)
M9_02-

C10- ModularRealmAuthenticator
M10_01- doAuthenticate(AuthenticationToken authenticationToken)
- 根据 Realm 数量 , 选择不同的认证类
- doSingleRealmAuthentication(realms.iterator().next(), authenticationToken) -> M10_02
- doMultiRealmAuthentication(realms, authenticationToken) -> M10_03
M10_02- doSingleRealmAuthentication
- AuthenticationInfo info = realm.getAuthenticationInfo(token)
M10_03- doMultiRealmAuthentication
M10_04- checkRole
- hasRole(principals, role) 判断是否 -> M10_05
M10_05- hasRole
FOR- getRealms() : 获取当前的 realms 类
- ((Authorizer) realm).hasRole(principals, roleIdentifier) : 调用 Reamlm 判断是否有 Role -> M11_04

C11- AuthenticatingRealm
M11_01- getAuthenticationInfo(AuthenticationToken token)
- getCachedAuthenticationInfo(token) : 获取缓存的 Authentication
- 调用 doGetAuthenticationInfo 进行实际的认证 : M12_02
- cacheAuthenticationInfoIfPossible 缓存认证信息
M11_02- cacheAuthenticationInfoIfPossible
- getAvailableAuthenticationCache() : 获取缓存集合
- getAuthenticationCacheKey(token) : 获取缓存 key
- cache.put(key, info) : 添加缓存
M11_03- assertCredentialsMatch
- CredentialsMatcher cm = getCredentialsMatcher();
- cm.doCredentialsMatch(token, info)
M11_04- hasRole
- AuthorizationInfo info = getAuthorizationInfo(principal)
-> M11_05
- hasRole(roleIdentifier, info)
M11_05- getAuthorizationInfo(PrincipalCollection principals)
?- 注意这里和 M11_01 的参数是不一样的
- getAvailableAuthorizationCache() 获取 Cache<Object, AuthorizationInfo>
- 如果 Cache 不为空 , getAuthorizationCacheKey 获取 key 后通过该key 从 Cache 里面获取 AuthorizationInfo
- 如果 缓存获取失败 , 则调用 doGetAuthorizationInfo(PrincipalCollection principals) 获取对象
?- 注意 , 这里要为其添加 Role -> M12_01



C12- CustomRealm
M12_01- AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection)

M12_02- AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)

3.4 Logout 的流程

logout 中做了哪些事 ?

logout 最终会调用 subject logout 操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
java复制代码    public void logout() {
try {
// 本质上是从 Session 中移除 .RUN_AS_PRINCIPALS_SESSION_KEY
clearRunAsIdentitiesInternal();
this.securityManager.logout(this);
} finally {
// 把 Subject
this.session = null;
this.principals = null;
this.authenticated = false;
}
}

C- DefaultSecurityManager
M- logout
- beforeLogout(subject)
- subject.getPrincipals() 获取一个 PrincipalCollection
- 再获取一个 Authenticator , 通过它来 onLogout PrincipalCollection
?- ((LogoutAware) authc).onLogout(principals)
?- 需要这一步是因为可能存在 缓存和多模块登录 , 需要同时退出
// 最后移除 session , 删除 subject
- delete(subject);
- this.subjectDAO.delete(subject)
- stopSession(subject);

Shiro 的 logout 看起来也很清晰 , session 一关 , subject 一删 , 完毕 .

甚至于都不用考虑是否需要重定向 , 一切都是业务自己决定.

3.5 补充一 : Shiro 的异常体系

很清晰 , Shiro 认证失败均会有响应的异常 , 由异常处理就可以决定业务的走向

Shiro-AccountException.png

3.6 补充二 : 细说 DefaultSubjectDAO

DefaultSubjectDAO 是其中一个比较重要的逻辑 , 它负责处理 Subject 的相关持久化 , 当然使用者中我们可以做一个自己的实现类来处理Subject 的操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
java复制代码
private SessionStorageEvaluator sessionStorageEvaluator;

// 主要看一下其中的 CURD 操作
M- saveToSession(Subject subject)
- mergePrincipals(subject);
- mergeAuthenticationState(subject);

M- mergePrincipals
?- 将主体当前的Subject#getPrincipals()与可能在其中的任何元素合并到任何可用的会话
- currentPrincipals = subject.getPrincipals();
- Session session = subject.getSession(false);
- session.removeAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
- session.setAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY, currentPrincipals)

// 不用多说什么 , 很清晰的就能看到 , 将 currentPrincipals 设置到了可用的 Session 中 , 也就是说 , Principals 其实是在 Session 中流转

M- mergeAuthenticationState
- session = subject.getSession();
- session.setAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY, Boolean.TRUE);
- session.removeAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY);

// 一样的 , 通过 Session 控制

3.7 Subject 的管理逻辑

之前看到 Subject 获取时 ,是通过 getSubject 获取的 , 看看这个类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
java复制代码
// 看了这个类大概就知道 , 为什么 shiro 支持多线程
public static Subject getSubject() {
Subject subject = ThreadContext.getSubject();
if (subject == null) {
subject = (new Subject.Builder()).buildSubject();
ThreadContext.bind(subject);
}
return subject;
}

// PS : ThreadContext 是 Shiro 自己的工具类


// TODO : 这里先留一个小坑 , 多线程的处理逻辑还没有专门分析 , 后续进行补充

四 . 扩展- 自行定义一个 OAuth 流程

因为Shiro 的特性 , 所以 OAuth 模式实际上是集成了其他的包

参考自 @ www.e-learn.cn/topic/15938… , 这一节不全 , 建议参考原文

Maven : 不要求一定是他们 , 其他的OAuth 实现均可

1
2
3
4
5
6
7
8
9
10
xml复制代码<dependency>
<groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.authzserver</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.resourceserver</artifactId>
<version>1.0.2</version>
</dependency>

其他的整体而言多的就是2个接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
java复制代码    @RequestMapping("/authorize")
public Object authorize(Model model, HttpServletRequest request)
throws URISyntaxException, OAuthSystemException {
logger.info("------ > 第一步 进入验证申请", request.toString());
try {
logger.info("------ > 第二步 生成 OAuthAuthzRequest", request.toString());
OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);
//检查传入的客户端id是否正确
if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
OAuthResponse response = OAuthASResponse
.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
.setError(OAuthError.TokenResponse.INVALID_CLIENT)
.setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
.buildJSONMessage();
return new ResponseEntity(
response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}
logger.info("step 3 获取 subject---:{}", SecurityUtils.getSubject().toString());
Subject subject = SecurityUtils.getSubject();
//如果用户没有登录,跳转到登陆页面
if (!subject.isAuthenticated()) {
if (!login(subject, request)) {//登录失败时跳转到登陆页面
model.addAttribute("client",
clientService.findByClientId(oauthRequest.getClientId()));
return "oauth2login";
}
}
logger.info("step 4 获取 username---:{}", (String) subject.getPrincipal());
String username = (String) subject.getPrincipal();
//生成授权码
String authorizationCode = null;
//responseType目前仅支持CODE,另外还有TOKEN
String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
if (responseType.equals(ResponseType.CODE.toString())) {
OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
authorizationCode = oauthIssuerImpl.authorizationCode();
logger.info("step 5 step -- authorizationCode :{}", authorizationCode);
oAuthService.addAuthCode(authorizationCode, username);
}
//进行OAuth响应构建
OAuthASResponse.OAuthAuthorizationResponseBuilder builder =
OAuthASResponse.authorizationResponse(request,
HttpServletResponse.SC_FOUND);
logger.info("step 5 step -- OAuthAuthorizationResponseBuilder :{}", builder);
//设置授权码
builder.setCode(authorizationCode);
//得到到客户端重定向地址
String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);

//构建响应
final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();
//根据OAuthResponse返回ResponseEntity响应
HttpHeaders headers = new HttpHeaders();
headers.setLocation(new URI(response.getLocationUri()));
return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
} catch (OAuthProblemException e) {
//出错处理
logger.info("step 2 进入authorize OAuthAuthzRequest---:{}", request.toString());
String redirectUri = e.getRedirectUri();
if (OAuthUtils.isEmpty(redirectUri)) {
//告诉客户端没有传入redirectUri直接报错
return new ResponseEntity(
"OAuth callback url needs to be provided by client!!!", HttpStatus.NOT_FOUND);
}
//返回错误消息(如?error=)
final OAuthResponse response =
OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND)
.error(e).location(redirectUri).buildQueryMessage();
HttpHeaders headers = new HttpHeaders();
headers.setLocation(new URI(response.getLocationUri()));
return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
}
}

private boolean login(Subject subject, HttpServletRequest request) {
if ("get".equalsIgnoreCase(request.getMethod())) {
return false;
}
String username = request.getParameter("username");
String password = request.getParameter("password");

if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
return false;
}

UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);
return true;
} catch (Exception e) {
request.setAttribute("error", "登录失败:" + e.getClass().getName());
return false;
}
}

AccessToken

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
java复制代码@RequestMapping("/accessToken")
public HttpEntity token(HttpServletRequest request)
throws URISyntaxException, OAuthSystemException {
try {
//构建OAuth请求
OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);
logger.info("step 1 OAuthTokenRequest request---:{}", oauthRequest.toString());
//检查提交的客户端id是否正确
if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
OAuthResponse response = OAuthASResponse
.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
.setError(OAuthError.TokenResponse.INVALID_CLIENT)
.setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
.buildJSONMessage();
return new ResponseEntity(
response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}

// 检查客户端安全KEY是否正确
if (!oAuthService.checkClientSecret(oauthRequest.getClientSecret())) {
OAuthResponse response = OAuthASResponse
.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
.setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT)
.setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
.buildJSONMessage();
return new ResponseEntity(
response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}
logger.info("step 1 authCode request---:{}",oauthRequest.getParam(OAuth.OAUTH_CODE));
String authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
// 检查验证类型,此处只检查AUTHORIZATION_CODE类型,其他的还有PASSWORD或REFRESH_TOKEN
if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(
GrantType.AUTHORIZATION_CODE.toString())) {
if (!oAuthService.checkAuthCode(authCode)) {
OAuthResponse response = OAuthASResponse
.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
.setError(OAuthError.TokenResponse.INVALID_GRANT)
.setErrorDescription("错误的授权码")
.buildJSONMessage();
return new ResponseEntity(
response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}
}

//生成Access Token
OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
final String accessToken = oauthIssuerImpl.accessToken();
logger.info("step 1 accessToken request---:{}",accessToken);
logger.info("step 1 username data---:{}", oAuthService.getUsernameByAuthCode(authCode));
oAuthService.addAccessToken(accessToken,
oAuthService.getUsernameByAuthCode(authCode));

//生成OAuth响应
OAuthResponse response = OAuthASResponse
.tokenResponse(HttpServletResponse.SC_OK)
.setAccessToken(accessToken)
.setExpiresIn(String.valueOf(oAuthService.getExpireIn()))
.buildJSONMessage();

//根据OAuthResponse生成ResponseEntity
return new ResponseEntity(
response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
} catch (OAuthProblemException e) {
//构建错误响应
OAuthResponse res = OAuthASResponse
.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
.buildJSONMessage();
return new ResponseEntity(res.getBody(), HttpStatus.valueOf(res.getResponseStatus()));
}
}

总结一下

简单点说 , 就是 Shiro 对 OAuth 没有支持 ,而想要获得 OAuth 能力 , 就自己定制 , 只是把 Shiro 当成一个内部 SSO , 获取用户信息即可

核心代码

1
2
java复制代码Subject subject = SecurityUtils.getSubject();
String username = (String) subject.getPrincipal();

总结

Shiro 这一篇也完了 , 真的很浅 ,没讲什么深入的东西, 一大原因是 Shiro 的定位就是大道至简 .

他只给你提供认证的能力 , 你也只需要把他当成一个内部 SSO , 通过相关方法认证 和 获取用户即可.

同时 ,他提供了细粒度的支持 , 与其他项目耦合低 , 我们曾经就在存在一个 认证框架的时候去集成他的 细粒度能力 , 因为它通过手动登录 , 基本上没什么冲突 , 也很好用.

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%