AuthorizationUtils

This commit is contained in:
MaxKey
2022-04-12 22:31:41 +08:00
parent 742b660453
commit 50bfb3087e
75 changed files with 766 additions and 1638 deletions
@@ -73,8 +73,7 @@ public class AuthorizeBaseEndpoint {
return app;
}
protected Accounts getAccounts(Apps app){
UserInfo userInfo = WebContext.getUserInfo();
protected Accounts getAccounts(Apps app,UserInfo userInfo){
Apps loadApp = getApp(app.getId());
Accounts account = new Accounts(userInfo.getId(),loadApp.getId());
@@ -97,7 +96,7 @@ public class AuthorizeBaseEndpoint {
);
//decoder database stored encode password
account.setRelatedPassword(
PasswordReciprocal.getInstance().decoder(WebContext.getUserInfo().getDecipherable()));
PasswordReciprocal.getInstance().decoder(userInfo.getDecipherable()));
}else if(loadApp.getCredential()==Apps.CREDENTIALS.NONE){
account.setUsername(userInfo.getUsername());
account.setRelatedPassword(userInfo.getUsername());
@@ -21,6 +21,8 @@
package org.maxkey.authz.endpoint;
import javax.servlet.http.HttpServletRequest;
import org.maxkey.authn.annotation.CurrentUser;
import org.maxkey.crypto.password.PasswordReciprocal;
import org.maxkey.entity.Accounts;
import org.maxkey.entity.UserInfo;
@@ -41,12 +43,13 @@ public class AuthorizeCredentialEndpoint extends AuthorizeBaseEndpoint{
@RequestMapping("/authz/credential/forward")
public ModelAndView authorizeCredentialForward(
@RequestParam("appId") String appId,
@RequestParam("redirect_uri") String redirect_uri){
@RequestParam("redirect_uri") String redirect_uri,
@CurrentUser UserInfo currentUser){
ModelAndView modelAndView=new ModelAndView("authorize/init_sso_credential");
modelAndView.addObject("username", "");
modelAndView.addObject("password", "");
modelAndView.addObject("setpassword", true);
modelAndView.addObject("userId", WebContext.getUserInfo().getId());
modelAndView.addObject("userId", currentUser.getId());
modelAndView.addObject("appId", appId);
modelAndView.addObject("appName",getApp(appId).getName());
modelAndView.addObject("redirect_uri", redirect_uri);
@@ -60,16 +63,17 @@ public class AuthorizeCredentialEndpoint extends AuthorizeBaseEndpoint{
@RequestParam("appId") String appId,
@RequestParam("identity_username") String identity_username,
@RequestParam("identity_password") String identity_password,
@RequestParam("redirect_uri") String redirect_uri){
@RequestParam("redirect_uri") String redirect_uri,
@CurrentUser UserInfo currentUser){
if(StringUtils.isNotEmpty(identity_username)&&StringUtils.isNotEmpty(identity_password)){
Accounts appUser =new Accounts ();
UserInfo userInfo=WebContext.getUserInfo();
appUser.setId(appUser.generateId());
appUser.setUserId(userInfo.getId());
appUser.setUsername(userInfo.getUsername());
appUser.setDisplayName(userInfo.getDisplayName());
appUser.setUserId(currentUser.getId());
appUser.setUsername(currentUser.getUsername());
appUser.setDisplayName(currentUser.getDisplayName());
appUser.setAppId(appId);
appUser.setAppName(getApp(appId).getName());
@@ -77,7 +81,7 @@ public class AuthorizeCredentialEndpoint extends AuthorizeBaseEndpoint{
appUser.setRelatedUsername(identity_username);
appUser.setRelatedPassword(PasswordReciprocal.getInstance().encode(identity_password));
appUser.setInstId(WebContext.getUserInfo().getInstId());
appUser.setInstId(currentUser.getInstId());
if(accountsService.insert(appUser)){
@@ -21,6 +21,8 @@
package org.maxkey.authz.endpoint;
import javax.servlet.http.HttpServletRequest;
import org.maxkey.authn.annotation.CurrentUser;
import org.maxkey.crypto.password.PasswordReciprocal;
import org.maxkey.entity.UserInfo;
import org.maxkey.web.WebConstants;
@@ -49,9 +51,9 @@ public class AuthorizeProtectedEndpoint{
@RequestMapping("/authz/protected")
public ModelAndView authorizeProtected(
@RequestParam("password") String password,
@RequestParam("redirect_uri") String redirect_uri){
UserInfo userInfo=WebContext.getUserInfo();
if( userInfo.getAppLoginPassword().equals(PasswordReciprocal.getInstance().encode(password))){
@RequestParam("redirect_uri") String redirect_uri,
@CurrentUser UserInfo currentUser){
if( currentUser.getAppLoginPassword().equals(PasswordReciprocal.getInstance().encode(password))){
WebContext.setAttribute(WebConstants.CURRENT_SINGLESIGNON_URI, redirect_uri);
return WebContext.redirect(redirect_uri);
}
@@ -26,8 +26,8 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.online.OnlineTicket;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.cas.endpoint.ticket.CasConstants;
import org.maxkey.authz.cas.endpoint.ticket.ServiceTicketImpl;
import org.maxkey.authz.singlelogout.LogoutType;
@@ -117,7 +117,7 @@ public class CasAuthorizeEndpoint extends CasBaseAuthorizeEndpoint{
HttpServletRequest request,
HttpServletResponse response){
AppsCasDetails casDetails = (AppsCasDetails)WebContext.getAttribute(CasConstants.PARAMETER.ENDPOINT_CAS_DETAILS);
ServiceTicketImpl serviceTicket = new ServiceTicketImpl(WebContext.getAuthentication(),casDetails);
ServiceTicketImpl serviceTicket = new ServiceTicketImpl(AuthorizationUtils.getAuthentication(),casDetails);
String ticket = ticketServices.createTicket(serviceTicket,casDetails.getExpires());
@@ -149,7 +149,7 @@ public class CasAuthorizeEndpoint extends CasBaseAuthorizeEndpoint{
}
if(casDetails.getLogoutType()==LogoutType.BACK_CHANNEL) {
String onlineTicketId = ((SigninPrincipal)WebContext.getAuthentication().getPrincipal()).getOnlineTicket().getTicketId();
String onlineTicketId = AuthorizationUtils.getPrincipal().getOnlineTicket().getTicketId();
OnlineTicket onlineTicket = onlineTicketService.get(onlineTicketId);
//set cas ticket as OnlineTicketId
casDetails.setOnlineTicket(ticket);
@@ -25,6 +25,7 @@ import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.AbstractAuthenticationProvider;
import org.maxkey.authn.LoginCredential;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.cas.endpoint.response.ServiceResponseBuilder;
import org.maxkey.authz.cas.endpoint.ticket.CasConstants;
import org.maxkey.authz.cas.endpoint.ticket.ServiceTicketImpl;
@@ -33,7 +34,6 @@ import org.maxkey.entity.UserInfo;
import org.maxkey.entity.apps.AppsCasDetails;
import org.maxkey.util.StringUtils;
import org.maxkey.web.HttpResponseConstants;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -85,7 +85,7 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{
authenticationProvider.authentication(loginCredential,false);
TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",WebContext.getAuthentication(),null);
TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",AuthorizationUtils.getAuthentication(),null);
String ticket=casTicketGrantingTicketServices.createTicket(ticketGrantingTicket);
String location = applicationConfig.getServerPrefix()+CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1 +"/" + ticket;
@@ -188,8 +188,8 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{
LoginCredential loginCredential =new LoginCredential(username,password,"CASREST");
authenticationProvider.authentication(loginCredential,false);
UserInfo userInfo =WebContext.getUserInfo();
TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",WebContext.getAuthentication(),null);
UserInfo userInfo = AuthorizationUtils.getUserInfo();
TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",AuthorizationUtils.getAuthentication(),null);
String ticket=casTicketGrantingTicketServices.createTicket(ticketGrantingTicket);
String location = applicationConfig.getServerPrefix() + CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1 + ticket;
@@ -22,14 +22,15 @@ package org.maxkey.authz.exapi.endpoint;
import javax.servlet.http.HttpServletRequest;
import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.annotation.CurrentUser;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.endpoint.AuthorizeBaseEndpoint;
import org.maxkey.authz.endpoint.adapter.AbstractAuthorizeAdapter;
import org.maxkey.constants.ConstsBoolean;
import org.maxkey.entity.Accounts;
import org.maxkey.entity.UserInfo;
import org.maxkey.entity.apps.Apps;
import org.maxkey.util.Instance;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
@@ -51,20 +52,23 @@ public class ExtendApiAuthorizeEndpoint extends AuthorizeBaseEndpoint{
@Operation(summary = "ExtendApi认证地址接口", description = "参数应用ID",method="GET")
@RequestMapping("/authz/api/{id}")
public ModelAndView authorize(HttpServletRequest request,@PathVariable("id") String id){
public ModelAndView authorize(
HttpServletRequest request,
@PathVariable("id") String id,
@CurrentUser UserInfo currentUser){
ModelAndView modelAndView=new ModelAndView("authorize/redirect_sso_submit");
Apps apps = getApp(id);
_logger.debug(""+apps);
if(ConstsBoolean.isTrue(apps.getIsAdapter())){
AbstractAuthorizeAdapter adapter = (AbstractAuthorizeAdapter)Instance.newInstance(apps.getAdapter());
Accounts account = getAccounts(apps);
Accounts account = getAccounts(apps,currentUser);
if(apps.getCredential()==Apps.CREDENTIALS.USER_DEFINED && account == null) {
return generateInitCredentialModelAndView(id,"/authorize/api/"+id);
}
adapter.setAuthentication((SigninPrincipal)WebContext.getAuthentication().getPrincipal());
adapter.setUserInfo(WebContext.getUserInfo());
adapter.setAuthentication(AuthorizationUtils.getPrincipal());
adapter.setUserInfo(currentUser);
adapter.setApp(apps);
adapter.setAccount(account);
@@ -22,17 +22,18 @@ package org.maxkey.authz.formbased.endpoint;
import javax.servlet.http.HttpServletRequest;
import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.annotation.CurrentUser;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.endpoint.AuthorizeBaseEndpoint;
import org.maxkey.authz.endpoint.adapter.AbstractAuthorizeAdapter;
import org.maxkey.authz.formbased.endpoint.adapter.FormBasedDefaultAdapter;
import org.maxkey.constants.ConstsBoolean;
import org.maxkey.entity.Accounts;
import org.maxkey.entity.UserInfo;
import org.maxkey.entity.apps.Apps;
import org.maxkey.entity.apps.AppsFormBasedDetails;
import org.maxkey.persistence.service.AppsFormBasedDetailsService;
import org.maxkey.util.Instance;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -62,7 +63,8 @@ public class FormBasedAuthorizeEndpoint extends AuthorizeBaseEndpoint{
@RequestMapping("/authz/formbased/{id}")
public ModelAndView authorize(
HttpServletRequest request,
@PathVariable("id") String id){
@PathVariable("id") String id,
@CurrentUser UserInfo currentUser){
AppsFormBasedDetails formBasedDetails = formBasedDetailsService.getAppDetails(id , true);
_logger.debug("formBasedDetails {}",formBasedDetails);
@@ -71,7 +73,7 @@ public class FormBasedAuthorizeEndpoint extends AuthorizeBaseEndpoint{
formBasedDetails.setIsAdapter(application.getIsAdapter());
ModelAndView modelAndView=null;
Accounts account = getAccounts(formBasedDetails);
Accounts account = getAccounts(formBasedDetails,currentUser);
_logger.debug("Accounts {}",account);
if(account == null){
@@ -88,8 +90,8 @@ public class FormBasedAuthorizeEndpoint extends AuthorizeBaseEndpoint{
FormBasedDefaultAdapter formBasedDefaultAdapter =new FormBasedDefaultAdapter();
adapter =(AbstractAuthorizeAdapter)formBasedDefaultAdapter;
}
adapter.setAuthentication((SigninPrincipal)WebContext.getAuthentication().getPrincipal());
adapter.setUserInfo(WebContext.getUserInfo());
adapter.setAuthentication(AuthorizationUtils.getPrincipal());
adapter.setUserInfo(currentUser);
adapter.setApp(formBasedDetails);
adapter.setAccount(account);
@@ -27,7 +27,8 @@ import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.annotation.CurrentUser;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.endpoint.AuthorizeBaseEndpoint;
import org.maxkey.authz.endpoint.adapter.AbstractAuthorizeAdapter;
import org.maxkey.authz.jwt.endpoint.adapter.JwtAdapter;
@@ -35,6 +36,7 @@ import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstsBoolean;
import org.maxkey.constants.ContentType;
import org.maxkey.crypto.jose.keystore.JWKSetKeyStore;
import org.maxkey.entity.UserInfo;
import org.maxkey.entity.apps.Apps;
import org.maxkey.entity.apps.AppsJwtDetails;
import org.maxkey.persistence.service.AppsJwtDetailsService;
@@ -76,7 +78,8 @@ public class JwtAuthorizeEndpoint extends AuthorizeBaseEndpoint{
public ModelAndView authorize(
HttpServletRequest request,
HttpServletResponse response,
@PathVariable("id") String id){
@PathVariable("id") String id,
@CurrentUser UserInfo currentUser){
ModelAndView modelAndView=new ModelAndView();
Apps application = getApp(id);
AppsJwtDetails jwtDetails = jwtDetailsService.getAppDetails(id , true);
@@ -98,8 +101,8 @@ public class JwtAuthorizeEndpoint extends AuthorizeBaseEndpoint{
adapter = (AbstractAuthorizeAdapter)jwtAdapter;
}
adapter.setAuthentication((SigninPrincipal)WebContext.getAuthentication().getPrincipal());
adapter.setUserInfo(WebContext.getUserInfo());
adapter.setAuthentication(AuthorizationUtils.getPrincipal());
adapter.setUserInfo(currentUser);
adapter.generateInfo();
//sign
@@ -19,7 +19,7 @@ package org.maxkey.authz.oauth2.provider.approval.endpoint;
import java.util.LinkedHashMap;
import java.util.Map;
import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.oauth2.common.OAuth2Constants;
import org.maxkey.authz.oauth2.provider.AuthorizationRequest;
import org.maxkey.authz.oauth2.provider.ClientDetailsService;
@@ -95,8 +95,7 @@ public class OAuth20AccessConfirmationEndpoint {
for (String scope : clientAuth.getScope()) {
scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + scope, "false");
}
String principal =
((SigninPrincipal) WebContext.getAuthentication().getPrincipal()).getUsername();
String principal = AuthorizationUtils.getPrincipal().getUsername();
for (Approval approval : approvalStore.getApprovals(principal, client.getClientId())) {
if (clientAuth.getScope().contains(approval.getScope())) {
scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + approval.getScope(),
@@ -22,6 +22,8 @@ import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.oauth2.common.OAuth2AccessToken;
import org.maxkey.authz.oauth2.common.OAuth2Constants;
import org.maxkey.authz.oauth2.common.exceptions.InvalidClientException;
@@ -150,7 +152,7 @@ public class AuthorizationEndpoint extends AbstractEndpoint {
@RequestParam Map<String, String> parameters,
SessionStatus sessionStatus) {
Principal principal=(Principal)WebContext.getAuthentication();
Principal principal=(Principal)AuthorizationUtils.getAuthentication();
// Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should
// query off of the authorization request instead of referring back to the parameters map. The contents of the
// parameters map will be stored without change in the AuthorizationRequest object once it is created.
@@ -241,7 +243,7 @@ public class AuthorizationEndpoint extends AbstractEndpoint {
Map<String, ?> model,
SessionStatus sessionStatus) {
Principal principal=(Principal)WebContext.getAuthentication();
Principal principal=(Principal)AuthorizationUtils.getAuthentication();
if (!(principal instanceof Authentication)) {
sessionStatus.setComplete();
throw new InsufficientAuthenticationException(
@@ -23,6 +23,7 @@ import java.util.Map;
import java.util.Set;
import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.oauth2.common.DefaultOAuth2AccessToken;
import org.maxkey.authz.oauth2.common.OAuth2AccessToken;
import org.maxkey.authz.oauth2.common.OAuth2Constants;
@@ -38,7 +39,6 @@ import org.maxkey.authz.oauth2.provider.TokenRequest;
import org.maxkey.authz.oauth2.provider.request.DefaultOAuth2RequestValidator;
import org.maxkey.entity.apps.oauth2.provider.ClientDetails;
import org.maxkey.util.StringGenerator;
import org.maxkey.web.WebContext;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
@@ -114,7 +114,7 @@ public class TokenEndpoint extends AbstractEndpoint {
// TokenEndpointAuthenticationFilter
OAuth2AccessToken token = null;
try {
Object principal = WebContext.getAuthentication();
Object principal = AuthorizationUtils.getAuthentication();
if (!(principal instanceof Authentication)) {
throw new InsufficientAuthenticationException(
@@ -32,6 +32,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.oauth2.common.OAuth2Constants;
import org.maxkey.authz.oauth2.common.util.OAuth2Utils;
import org.maxkey.authz.oauth2.provider.AuthorizationRequest;
@@ -154,7 +155,7 @@ public class TokenEndpointAuthenticationFilter implements Filter {
}
auth.setAuthenticated(true);
UsernamePasswordAuthenticationToken simpleUserAuthentication = new UsernamePasswordAuthenticationToken(auth, authentication.getCredentials(), authentication.getAuthorities());
WebContext.setAuthentication(simpleUserAuthentication);
AuthorizationUtils.setAuthentication(simpleUserAuthentication);
}
}
@@ -208,7 +209,7 @@ public class TokenEndpointAuthenticationFilter implements Filter {
OAuth2Request storedOAuth2Request = oAuth2RequestFactory.createOAuth2Request(authorizationRequest);
WebContext.setAuthentication(new OAuth2Authentication(storedOAuth2Request, authResult));
AuthorizationUtils.setAuthentication(new OAuth2Authentication(storedOAuth2Request, authResult));
onSuccessfulAuthentication(request, response, authResult);
@@ -30,6 +30,7 @@ import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.oauth2.common.DefaultOAuth2AccessToken;
import org.maxkey.authz.oauth2.common.OAuth2AccessToken;
import org.maxkey.authz.oauth2.provider.ClientDetailsService;
@@ -40,7 +41,6 @@ import org.maxkey.configuration.oidc.OIDCProviderMetadata;
import org.maxkey.crypto.jwt.encryption.service.impl.DefaultJwtEncryptionAndDecryptionService;
import org.maxkey.crypto.jwt.signer.service.impl.DefaultJwtSigningAndValidationService;
import org.maxkey.entity.apps.oauth2.provider.ClientDetails;
import org.maxkey.web.WebContext;
import com.nimbusds.jose.util.Base64URL;
import org.slf4j.Logger;
@@ -125,7 +125,7 @@ public class OIDCIdTokenEnhancer implements TokenEnhancer {
if (request.getExtensions().containsKey("max_age")
|| (request.getExtensions().containsKey("idtoken")) // parse the ID Token claims (#473) -- for now assume it could be in there
) {
DateTime loginDate = DateTime.parse(WebContext.getUserInfo().getLastLoginTime(), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
DateTime loginDate = DateTime.parse(AuthorizationUtils.getUserInfo().getLastLoginTime(), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
builder.claim("auth_time", loginDate.getMillis()/1000);
}
@@ -22,14 +22,15 @@ import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.annotation.CurrentUser;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.saml.common.AuthnRequestInfo;
import org.maxkey.authz.saml.common.EndpointGenerator;
import org.maxkey.authz.saml20.binding.BindingAdapter;
import org.maxkey.authz.saml20.provider.xml.AuthnResponseGenerator;
import org.maxkey.entity.UserInfo;
import org.maxkey.entity.apps.AppsSAML20Details;
import org.maxkey.web.WebConstants;
import org.maxkey.web.WebContext;
import org.opensaml.saml2.core.Response;
import org.opensaml.saml2.metadata.Endpoint;
import org.opensaml.ws.message.encoder.MessageEncodingException;
@@ -57,7 +58,10 @@ public class AssertionEndpoint {
AuthnResponseGenerator authnResponseGenerator;
@RequestMapping(value = "/authz/saml20/assertion")
public ModelAndView assertion(HttpServletRequest request,HttpServletResponse response) throws Exception {
public ModelAndView assertion(
HttpServletRequest request,
HttpServletResponse response,
@CurrentUser UserInfo currentUser) throws Exception {
logger.debug("saml20 assertion start.");
bindingAdapter = (BindingAdapter) request.getSession().getAttribute(
WebConstants.AUTHORIZE_SIGN_ON_APP_SAMLV20_ADAPTER);
@@ -74,14 +78,15 @@ public class AssertionEndpoint {
logger.debug("AuthnRequestInfo: {}", authnRequestInfo);
HashMap <String,String>attributeMap=new HashMap<String,String>();
attributeMap.put(WebConstants.ONLINE_TICKET_NAME,
((SigninPrincipal)WebContext.getAuthentication().getPrincipal()).getOnlineTicket().getTicketId());
AuthorizationUtils.getPrincipal().getOnlineTicket().getTicketId());
//saml20Details
Response authResponse = authnResponseGenerator.generateAuthnResponse(
saml20Details,
authnRequestInfo,
attributeMap,
bindingAdapter);
bindingAdapter,
currentUser);
Endpoint endpoint = endpointGenerator.generateEndpoint(saml20Details.getSpAcsUrl());
@@ -21,10 +21,12 @@ import java.util.ArrayList;
import java.util.HashMap;
import org.joda.time.DateTime;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.saml.service.IDService;
import org.maxkey.authz.saml.service.TimeService;
import org.maxkey.authz.saml20.binding.BindingAdapter;
import org.maxkey.authz.saml20.xml.IssuerGenerator;
import org.maxkey.entity.UserInfo;
import org.maxkey.entity.apps.AppsSAML20Details;
import org.maxkey.web.WebContext;
import org.opensaml.Configuration;
@@ -79,7 +81,8 @@ public class AssertionGenerator {
String inResponseTo,
String audienceUrl,
int validInSeconds,
HashMap<String,String>attributeMap
HashMap<String,String>attributeMap,
UserInfo userInfo
) {
Assertion assertion = new AssertionBuilder().buildObject();;
@@ -88,7 +91,8 @@ public class AssertionGenerator {
saml20Details,
assertionConsumerURL,
inResponseTo,
validInSeconds);
validInSeconds,
userInfo);
assertion.setSubject(subject);
//issuer
Issuer issuer = issuerGenerator.generateIssuer();
@@ -100,11 +104,15 @@ public class AssertionGenerator {
//AttributeStatements
ArrayList<GrantedAuthority> grantedAuthoritys = new ArrayList<GrantedAuthority>();
grantedAuthoritys.add(new SimpleGrantedAuthority("ROLE_USER"));
for(GrantedAuthority anthGrantedAuthority: ((UsernamePasswordAuthenticationToken)WebContext.getAuthentication()).getAuthorities()){
for(GrantedAuthority anthGrantedAuthority: ((UsernamePasswordAuthenticationToken)AuthorizationUtils.getAuthentication()).getAuthorities()){
grantedAuthoritys.add(anthGrantedAuthority);
}
AttributeStatement attributeStatement =attributeStatementGenerator.generateAttributeStatement(
saml20Details, grantedAuthoritys,attributeMap);
AttributeStatement attributeStatement =
attributeStatementGenerator.generateAttributeStatement(
saml20Details,
grantedAuthoritys,
attributeMap,
userInfo);
assertion.getAttributeStatements().add(attributeStatement);
//ID
assertion.setID(idService.generateID());
@@ -30,7 +30,6 @@ import org.maxkey.entity.ExtraAttr;
import org.maxkey.entity.ExtraAttrs;
import org.maxkey.entity.UserInfo;
import org.maxkey.entity.apps.AppsSAML20Details;
import org.maxkey.web.WebContext;
import org.opensaml.Configuration;
import org.opensaml.saml2.core.Attribute;
import org.opensaml.saml2.core.AttributeStatement;
@@ -52,15 +51,20 @@ public class AttributeStatementGenerator {
public static String COMMA = ",";
public static String COMMA_ISO8859_1 = "#44;"; //#44; ->,
public AttributeStatement generateAttributeStatement(AppsSAML20Details saml20Details,ArrayList<GrantedAuthority> grantedAuthoritys) {
return generateAttributeStatement(saml20Details, grantedAuthoritys,null);
public AttributeStatement generateAttributeStatement(
AppsSAML20Details saml20Details,
ArrayList<GrantedAuthority> grantedAuthoritys,
UserInfo userInfo) {
return generateAttributeStatement(
saml20Details, grantedAuthoritys,null,userInfo);
}
public AttributeStatement generateAttributeStatement(
AppsSAML20Details saml20Details,
ArrayList<GrantedAuthority> grantedAuthoritys,
HashMap<String,String>attributeMap) {
HashMap<String,String>attributeMap,
UserInfo userInfo) {
AttributeStatementBuilder attributeStatementBuilder = (AttributeStatementBuilder) builderFactory.getBuilder(AttributeStatement.DEFAULT_ELEMENT_NAME);
AttributeStatement attributeStatement = attributeStatementBuilder.buildObject();
@@ -68,7 +72,7 @@ public class AttributeStatementGenerator {
Attribute attributeGrantedAuthority=builderGrantedAuthority(grantedAuthoritys);
attributeStatement.getAttributes().add(attributeGrantedAuthority);
putUserAttributes(attributeMap);
putUserAttributes(attributeMap,userInfo);
if(null!=attributeMap){
Iterator<Entry<String, String>> iterator = attributeMap.entrySet().iterator();
@@ -137,8 +141,9 @@ public class AttributeStatementGenerator {
return xsStringValue;
}
public HashMap <String,String> putUserAttributes(HashMap <String,String> attributeMap){
UserInfo userInfo = WebContext.getUserInfo();
public HashMap <String,String> putUserAttributes(
HashMap <String,String> attributeMap,
UserInfo userInfo){
attributeMap.put(ActiveDirectoryUser.USERNAME, userInfo.getUsername());
attributeMap.put(ActiveDirectoryUser.UID, userInfo.getUsername());
@@ -26,6 +26,7 @@ import org.maxkey.authz.saml.service.TimeService;
import org.maxkey.authz.saml20.binding.BindingAdapter;
import org.maxkey.authz.saml20.xml.IssuerGenerator;
import org.maxkey.constants.ConstsBoolean;
import org.maxkey.entity.UserInfo;
import org.maxkey.entity.apps.AppsSAML20Details;
import org.opensaml.Configuration;
import org.opensaml.saml2.core.Assertion;
@@ -64,7 +65,8 @@ public class AuthnResponseGenerator {
public Response generateAuthnResponse( AppsSAML20Details saml20Details,
AuthnRequestInfo authnRequestInfo,
HashMap<String,String>attributeMap,
BindingAdapter bindingAdapter){
BindingAdapter bindingAdapter,
UserInfo currentUser){
Response authResponse = new ResponseBuilder().buildObject();
//builder Assertion
@@ -75,7 +77,8 @@ public class AuthnResponseGenerator {
authnRequestInfo.getAuthnRequestID(),
saml20Details.getAudience(),
Integer.parseInt(saml20Details.getValidityInterval()),
attributeMap);
attributeMap,
currentUser);
//Encrypt
if(ConstsBoolean.isYes(saml20Details.getEncrypted())) {
@@ -47,8 +47,8 @@ public class SubjectGenerator {
public Subject generateSubject( AppsSAML20Details saml20Details,
String assertionConsumerURL,
String inResponseTo,
int validInSeconds) {
UserInfo userInfo = WebContext.getUserInfo();
int validInSeconds,
UserInfo userInfo) {
String nameIdValue = userInfo.getUsername();
if(saml20Details.getNameidFormat().equalsIgnoreCase("persistent")) {
@@ -24,12 +24,14 @@ import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.annotation.CurrentUser;
import org.maxkey.authn.web.AuthorizationUtils;
import org.maxkey.authz.endpoint.AuthorizeBaseEndpoint;
import org.maxkey.authz.endpoint.adapter.AbstractAuthorizeAdapter;
import org.maxkey.authz.token.endpoint.adapter.TokenBasedDefaultAdapter;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstsBoolean;
import org.maxkey.entity.UserInfo;
import org.maxkey.entity.apps.Apps;
import org.maxkey.entity.apps.AppsTokenBasedDetails;
import org.maxkey.persistence.service.AppsTokenBasedDetailsService;
@@ -66,7 +68,8 @@ public class TokenBasedAuthorizeEndpoint extends AuthorizeBaseEndpoint{
public ModelAndView authorize(
HttpServletRequest request,
HttpServletResponse response,
@PathVariable("id") String id){
@PathVariable("id") String id,
@CurrentUser UserInfo currentUser){
ModelAndView modelAndView=new ModelAndView();
@@ -84,8 +87,8 @@ public class TokenBasedAuthorizeEndpoint extends AuthorizeBaseEndpoint{
}else{
adapter =(AbstractAuthorizeAdapter)new TokenBasedDefaultAdapter();
}
adapter.setAuthentication((SigninPrincipal)WebContext.getAuthentication().getPrincipal());
adapter.setUserInfo(WebContext.getUserInfo());
adapter.setAuthentication(AuthorizationUtils.getPrincipal());
adapter.setUserInfo(currentUser);
adapter.setApp(tokenBasedDetails);
adapter.generateInfo();