如何在@Controller中提取身份验证令牌 [英] How to extract authentication token in @Controller
问题描述
我有使用OAuth 2.0和授权服务器的Spring Boot应用程序.当我尝试访问安全页面时,我在我的授权服务器(Blitz Identity Provider)的登录页面上获得了重定向,并且这里的一切工作都应该正常进行.我的问题是我无法在@Controller(在安全页面上)中提取授权令牌.我想稍后在第二个应用程序中使用该令牌进行授权.
I have Spring Boot app that uses OAuth 2.0 and Authorization Server. When I try to access secured page, I got redirect on login page of my authorization server (Blitz Identity Provider) and everything works great here like it should. My problem is that I can't extract authorization token in @Controller (on secured page). That token I want to use later to authorize in second application.
- 尝试了这件事(作为回答),它奏效了,我拿回了我的令牌, 但是如您所见,它是用户名和密码的硬编码 参数,就像通过登录登录-我不需要登录 第二次(在经过身份验证的页面上).
- 试图输出 authentication.getDetails(),它显示令牌类型 和<令牌> ,但这还不够.
- 试图在请求响应标头中查找令牌,但未找到 它,因此授权服务器不会在标头中发送它.
- Tried this thing (in answer) and it worked, I got my token back, but as you can see, it's a hardcode of username and password parameters and it's like login over login -- I don't need to login for a second time (on authenticated page).
- Tried to output authentication.getDetails(), it shows token type and token like < TOKEN >, but it's not enough.
- Tried to lookup token in request-response headers, but didn't find it, so authorization server doesn't send it in headers.
这里有2个文件,可以帮助您了解我的情况的一部分.
Here are 2 files which can help you to understand some part of my context.
application.yml
server:
port: 8080
context-path: /
session:
cookie:
name:FIRSTSESSION
security:
basic:
enabled: false
oauth2:
client:
clientId: test_id
clientSecret: f3M5m9a2Dn0v15l
accessTokenUri: http://server:9000/blitz/oauth/te
userAuthorizationUri: http://server:9000/blitz/oauth/ae?scope=test_scope
resource:
userInfoUri: http://server:9000/blitz/oauth/me
logging:
level:
org.springframework.security: DEBUG
SsoController.java
@EnableOAuth2Sso
@Controller
public class SsoController {
@RequestMapping("/secondService")
public String getContent(HttpServletRequest request, Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
model.addAttribute("submittedValue", authentication.getDetails());
return "secondService";
}
}
那么,您有什么建议?在这种情况下如何提取授权令牌?
So, what you can suggest? How can I extract authorization token in this case?
推荐答案
如果您已配置oauth2授权/资源服务器,则可以尝试以下代码:
If you have configured oauth2 authorization/resource server you can try below code:
@Autowired
private TokenStore tokenStore;
@RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/oauth/me")
public Map<String, Object> userInfo(OAuth2Authentication auth){
final OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails();
//token
String accessToken = details.getTokenValue();
//reference
final OAuth2AccessToken accessToken = tokenStore.readAccessToken(details.getTokenValue());
// clientid
String clientId = auth.getOAuth2Request().getClientId();
}
希望有帮助!
这篇关于如何在@Controller中提取身份验证令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!