本文整理汇总了Java中org.keycloak.representations.AccessToken类的典型用法代码示例。如果您正苦于以下问题:Java AccessToken类的具体用法?Java AccessToken怎么用?Java AccessToken使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
AccessToken类属于org.keycloak.representations包,在下文中一共展示了AccessToken类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: verifyToken
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
@Override
public String verifyToken(String accessToken) {
String userId = "";
try {
PublicKey publicKey = toPublicKey(SSO_PUBLIC_KEY);
AccessToken token = RSATokenVerifier.verifyToken(accessToken, publicKey,
KeyCloakConnectionProvider.SSO_URL + "realms/" + KeyCloakConnectionProvider.SSO_REALM,
true, true);
userId = token.getSubject();
ProjectLogger.log(
token.getId() + " " + token.issuedFor + " " + token.getProfile() + " "
+ token.getSubject() + " Active== " + token.isActive() + " isExpired=="
+ token.isExpired() + " " + token.issuedNow().getExpiration(),
LoggerEnum.INFO.name());
} catch (Exception e) {
ProjectLogger.log("User token is not authorized==" + e);
throw new ProjectCommonException(ResponseCode.unAuthorised.getErrorCode(),
ResponseCode.unAuthorised.getErrorMessage(), ResponseCode.UNAUTHORIZED.getResponseCode());
}
return userId;
}
示例2: generateKeycloakToken
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
/**
* Helper function of build fake KeycloakAuthenticationToken
* @param orgMrn
* @param roles
* @param permissions
* @return
*/
public static KeycloakAuthenticationToken generateKeycloakToken(String orgMrn, String roles, String permissions) {
AccessToken accessToken = new AccessToken();
if (orgMrn != null && !orgMrn.isEmpty()) {
accessToken.setOtherClaims(AccessControlUtil.ORG_PROPERTY_NAME, orgMrn);
}
if (permissions != null && !permissions.isEmpty()) {
accessToken.setOtherClaims(AccessControlUtil.PERMISSIONS_PROPERTY_NAME, permissions);
}
RefreshableKeycloakSecurityContext ksc = new RefreshableKeycloakSecurityContext(null, null, "accessTokenString", accessToken, "idTokenString", null, "refreshTokenString");
Set<String> rolesSet = new HashSet<>();
String[] roleArr = roles.split(",");
for(String role : roleArr) {
rolesSet.add(role.trim());
}
KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<>("name", ksc);
SimpleKeycloakAccount account = new SimpleKeycloakAccount(principal, rolesSet, ksc);
Collection<GrantedAuthority> authorities = generateGrantedAuthority(roles);
return new KeycloakAuthenticationToken(account, authorities);
}
示例3: getKeycloakAuthentication
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
public KeycloakAuthentication getKeycloakAuthentication(HttpServletRequest request) throws Exception {
String redirect = redirectUrl(request);
AccessTokenResponse tokenResponse = ServerRequest.invokeAccessCodeToToken(keycloakDeployment, request.getParameter("code"), redirect, null);
String idTokenString = tokenResponse.getIdToken();
String refreashToken = tokenResponse.getRefreshToken();
String tokenString = tokenResponse.getToken();
AccessToken token = RSATokenVerifier.verifyToken(tokenString, keycloakDeployment.getRealmKey(), keycloakDeployment.getRealm());
if (idTokenString != null) {
JWSInput input = new JWSInput(idTokenString);
IDToken idToken = input.readJsonContent(IDToken.class);
return new KeycloakAuthentication(idToken, token, refreashToken);
}
throw new RuntimeException("Invalid User ");
}
示例4: doTokenAuth
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
private Holder<Boolean> doTokenAuth(Holder<Boolean> successStatus, ApiRequest request,
IPolicyContext context, KeycloakOauthConfigBean config, IPolicyChain<ApiRequest> chain,
String rawToken) {
try {
AccessToken parsedToken = RSATokenVerifier.verifyToken(rawToken, config.getRealmCertificate()
.getPublicKey(), config.getRealm());
delegateKerberosTicket(request, config, parsedToken);
forwardHeaders(request, config, rawToken, parsedToken);
stripAuthTokens(request, config);
forwardAuthRoles(context, config, parsedToken);
RequestMetric metric = context.getAttribute(PolicyContextKeys.REQUEST_METRIC, (RequestMetric) null);
if (metric != null) {
metric.setUser(parsedToken.getPreferredUsername());
}
return successStatus.setValue(true);
} catch (VerificationException e) {
System.out.println(e);
chain.doFailure(failureFactory.verificationException(context, e));
return successStatus.setValue(false);
}
}
示例5: forwardAuthRoles
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
private void forwardAuthRoles(IPolicyContext context, KeycloakOauthConfigBean config,
AccessToken parsedToken) {
if (config.getForwardRoles().getActive()) {
Access access = null;
if (config.getForwardRoles().getApplicationName() != null) {
access = parsedToken.getResourceAccess(config.getForwardRoles().getApplicationName());
} else {
access = parsedToken.getRealmAccess();
}
if (access == null || access.getRoles() == null) {
context.setAttribute(AuthorizationPolicy.AUTHENTICATED_USER_ROLES, Collections.<String>emptySet());
} else {
context.setAttribute(AuthorizationPolicy.AUTHENTICATED_USER_ROLES, access.getRoles());
}
}
}
示例6: createKeycloakSecurityContext
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
/**
* Creates a new {@link RefreshableKeycloakSecurityContext} from the given {@link KeycloakDeployment} and {@link AccessTokenResponse}.
*
* @param deployment the <code>KeycloakDeployment</code> for which to create a <code>RefreshableKeycloakSecurityContext</code> (required)
* @param accessTokenResponse the <code>AccessTokenResponse</code> from which to create a RefreshableKeycloakSecurityContext (required)
*
* @return a <code>RefreshableKeycloakSecurityContext</code> created from the given <code>accessTokenResponse</code>
* @throws VerificationException if the given <code>AccessTokenResponse</code> contains an invalid {@link IDToken}
*/
public static RefreshableKeycloakSecurityContext createKeycloakSecurityContext(KeycloakDeployment deployment, AccessTokenResponse accessTokenResponse) throws VerificationException {
String tokenString = accessTokenResponse.getToken();
String idTokenString = accessTokenResponse.getIdToken();
AccessToken accessToken = RSATokenVerifier
.verifyToken(tokenString, deployment.getRealmKey(), deployment.getRealmInfoUrl());
IDToken idToken;
try {
JWSInput input = new JWSInput(idTokenString);
idToken = input.readJsonContent(IDToken.class);
} catch (JWSInputException e) {
throw new VerificationException("Unable to verify ID token", e);
}
// FIXME: does it make sense to pass null for the token store?
return new RefreshableKeycloakSecurityContext(deployment, null, tokenString, accessToken, idTokenString, idToken, accessTokenResponse.getRefreshToken());
}
示例7: basicWorkflow
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
@Test
public void basicWorkflow()
throws Exception
{
final SimpleAuthService authService = mock( SimpleAuthService.class );
final SimpleSecureSessionManager sm = new SimpleSecureSessionManager();
setField( sm, authService );
final String userID = ValueUtil.randomString();
final OidcKeycloakAccount account = mock( OidcKeycloakAccount.class );
final AccessToken token = new AccessToken();
setField( token, userID );
final KeycloakSecurityContext context =
new KeycloakSecurityContext( ValueUtil.randomString(), token, ValueUtil.randomString(), new IDToken() );
when( account.getKeycloakSecurityContext() ).thenReturn( context );
when( authService.findAccount() ).thenReturn( account );
final SessionInfo sessionInfo = sm.createSession();
assertNotNull( sessionInfo );
assertEquals( sessionInfo.getUserID(), userID );
}
示例8: setUp
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
/**
* Basic setup stuff, needed for all the UPS related service classes
*/
@Before
public void setUp(){
// Keycloak test environment
AccessToken token = new AccessToken();
//The current developer will always be the admin in this testing scenario
token.setPreferredUsername("admin");
when(context.getToken()).thenReturn(token);
when(keycloakPrincipal.getKeycloakSecurityContext()).thenReturn(context);
when(httpServletRequest.getUserPrincipal()).thenReturn(keycloakPrincipal);
// glue it to serach mgr
searchManager.setHttpServletRequest(httpServletRequest);
// more to setup ?
specificSetup();
}
示例9: createToken
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
public AccessToken createToken() {
AccessToken token = new AccessToken();
token.id("token-id");
token.subject("user-id");
token.audience(realm);
token.expiration(Time.currentTime() + 300);
token.issuedFor("app-id");
token.issuedNow();
token.setGivenName("given");
token.setFamilyName("family");
token.setEmail("email");
token.setRealmAccess(new AccessToken.Access().roles(Collections.singleton("realm-role")));
token.addAccess("app-id").roles(Collections.singleton("app-role"));
token.addAccess("app2-id").roles(Collections.singleton("app-role"));
return token;
}
示例10: testTokenInfo
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
@Test
public void testTokenInfo() throws Exception {
RequestContext requestContext = new RequestContext.Builder().build();
AccessToken token = tokenUtil.createToken();
ResourceState returnedState = client.read(requestContext, "/testApp/auth/token-info/" + tokenUtil.toString(token));
assertEquals(tokenUtil.realm(), returnedState.getProperty("realm"));
assertEquals("user-id", returnedState.getProperty("subject"));
assertEquals(token.getIssuedAt(), ((Date) returnedState.getProperty("issued-at")).getTime());
List<String> roles = (List<String>) returnedState.getProperty("roles");
assertEquals(3, roles.size());
assertTrue(roles.contains("realm-role"));
assertTrue(roles.contains("app-id/app-role"));
assertTrue(roles.contains("app2-id/app-role"));
}
示例11: olaSecured
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
@CrossOrigin
@RequestMapping(method = RequestMethod.GET, value = "/ola-secured", produces = "text/plain")
@ApiOperation("Returns a message that is only available for authenticated users")
public String olaSecured(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) {
AccessToken token = principal.getKeycloakSecurityContext().getToken();
return "This is a Secured resource. You are logged as " + token.getName();
}
示例12: buildRoles
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
private static GrantedAuthority[] buildRoles(AccessToken accessToken) {
List<GrantedAuthority> roles;
roles = new ArrayList<GrantedAuthority>();
if (accessToken != null && accessToken.getRealmAccess() != null) {
for (String role : accessToken.getRealmAccess().getRoles()) {
roles.add(new GrantedAuthorityImpl(role));
}
}
roles.add(SecurityRealm.AUTHENTICATED_AUTHORITY);
return roles.toArray(new GrantedAuthority[roles.size()]);
}
示例13: helloAdvanced
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
@Override
public String helloAdvanced() {
Principal principal = ctx.getCallerPrincipal();
Subject subject = getSecurityContext().getSubjectInfo().getAuthenticatedSubject();
Set<KeycloakPrincipal> keycloakPrincipals = subject.getPrincipals(KeycloakPrincipal.class);
KeycloakPrincipal kcPrincipal = keycloakPrincipals.iterator().next();
AccessToken accessToken = kcPrincipal.getKeycloakSecurityContext().getToken();
return "Advanced - Hello " + accessToken.getName();
}
示例14: createUserDetails
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
@SuppressWarnings("unchecked")
private Object createUserDetails(NativeWebRequest webRequest) {
KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal =
(KeycloakPrincipal<RefreshableKeycloakSecurityContext>) webRequest.getUserPrincipal();
AccessToken token = principal.getKeycloakSecurityContext().getToken();
return new UserDetails(token.getId(), token.getGivenName(), token.getFamilyName(), token.getEmail(),
token.getRealmAccess().getRoles());
}
示例15: olaSecured
import org.keycloak.representations.AccessToken; //导入依赖的package包/类
@CrossOrigin
@RequestMapping(method = RequestMethod.GET, value = "/ola-secured", produces = "text/plain")
@ApiOperation("Returns a message that is only available for authenticated users")
public String olaSecured(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) {
AccessToken token = principal.getKeycloakSecurityContext().getToken();
return "This is a Secured resource. You are logged as " + token.getName();
}