Java Code Examples for org.springframework.security.oauth2.provider.AuthorizationRequest

The following examples show how to use org.springframework.security.oauth2.provider.AuthorizationRequest. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: open-cloud   Source File: IndexController.java    License: MIT License 6 votes vote down vote up
/**
 * 确认授权页
 * @param request
 * @param session
 * @param model
 * @return
 */
@RequestMapping("/oauth/confirm_access")
public String confirm_access(HttpServletRequest request, HttpSession session, Map model) {
    Map<String, String> scopes = (Map<String, String>) (model.containsKey("scopes") ? model.get("scopes") : request.getAttribute("scopes"));
    List<String> scopeList = new ArrayList<String>();
    for (String scope : scopes.keySet()) {
        scopeList.add(scope);
    }
    model.put("scopeList", scopeList);
    Object auth = session.getAttribute("authorizationRequest");
    if (auth != null) {
        try {
            AuthorizationRequest authorizationRequest = (AuthorizationRequest) auth;
            ClientDetails clientDetails = baseAppRemoteService.getAppClientInfo(authorizationRequest.getClientId()).getData();
            model.put("app", clientDetails.getAdditionalInformation());
        } catch (Exception e) {

        }
    }
    return "confirm_access";
}
 
Example 2
Source Project: open-cloud   Source File: IndexController.java    License: MIT License 6 votes vote down vote up
/**
 * 确认授权页
 * @param request
 * @param session
 * @param model
 * @return
 */
@RequestMapping("/oauth/confirm_access")
public String confirm_access(HttpServletRequest request, HttpSession session, Map model) {
    Map<String, String> scopes = (Map<String, String>) (model.containsKey("scopes") ? model.get("scopes") : request.getAttribute("scopes"));
    List<String> scopeList = new ArrayList<String>();
    for (String scope : scopes.keySet()) {
        scopeList.add(scope);
    }
    model.put("scopeList", scopeList);
    Object auth = session.getAttribute("authorizationRequest");
    if (auth != null) {
        try {
            AuthorizationRequest authorizationRequest = (AuthorizationRequest) auth;
            ClientDetails clientDetails = baseAppRemoteService.getAppClientInfo(authorizationRequest.getClientId()).getData();
            model.put("app", clientDetails.getAdditionalInformation());
        } catch (Exception e) {

        }
    }
    return "confirm_access";
}
 
Example 3
Source Project: spring-boot   Source File: AccessConfirmationController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model, Principal principal) throws Exception {
    AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest");
    ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
    model.put("auth_request", clientAuth);
    model.put("client", client);
    Map<String, String> scopes = new LinkedHashMap<String, String>();
    for (String scope : clientAuth.getScope()) {
        scopes.put(OAuth2Utils.SCOPE_PREFIX + scope, "false");
    }
    for (Approval approval : approvalStore.getApprovals(principal.getName(), client.getClientId())) {
        if (clientAuth.getScope().contains(approval.getScope())) {
            scopes.put(OAuth2Utils.SCOPE_PREFIX + approval.getScope(),
                    approval.getStatus() == Approval.ApprovalStatus.APPROVED ? "true" : "false");
        }
    }
    model.put("scopes", scopes);
    return new ModelAndView("access_confirmation", model); // 订阅 appproval 页面
}
 
Example 4
Source Project: osiam   Source File: AccessConfirmationController.java    License: MIT License 6 votes vote down vote up
@RequestMapping("/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model) {

    AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest");
    if (clientAuth == null) {
        return new ModelAndView("redirect:/oauth/error");
    }
    String clientId = clientAuth.getClientId();
    ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
    if (client == null) {
        return new ModelAndView("redirect:/oauth/error");
    }
    model.put("auth_request", clientAuth);
    model.put("client", client);
    model.put("loginError", false);

    return new ModelAndView("access_confirmation", model);
}
 
Example 5
Source Project: osiam   Source File: OsiamUserApprovalHandler.java    License: MIT License 6 votes vote down vote up
private boolean hasRememberedApprovalForClient(AuthorizationRequest authorizationRequest, ClientDetails client) {
    @SuppressWarnings("unchecked")
    Map<String, Long> approvals = (Map<String, Long>) httpSession.getAttribute(APPROVALS_SESSION_KEY);

    if (approvals == null) {
        return false;
    }

    final Long approvalTime = approvals.get(authorizationRequest.getClientId());

    if (approvalTime == null) {
        return false;
    }

    final long validityInSeconds = (Long) client.getAdditionalInformation().get("validityInSeconds");

    if (System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(validityInSeconds) > approvalTime) {
        approvals.remove(authorizationRequest.getClientId());
        return false;
    }

    return true;
}
 
Example 6
/**
 * Ensure redirect uri is authorized.
 *
 * @param authorizationRequest the authorization request
 * @param client               the client
 */
private static void ensureRedirectUriIsAuthorized(final AuthorizationRequest authorizationRequest, 
                                           final ClientDetailsEntity client) {
    if (!Strings.isNullOrEmpty(authorizationRequest.getRedirectUri())) {
        boolean found = false;
        final Iterator<String> it = client.getRedirectUris().iterator();

        while (!found && it.hasNext()) {
            found = it.next().equals(authorizationRequest.getRedirectUri());
        }
        if (!found) {
            throw new OIDCException("Redirect uri in the authorization request " +
                    authorizationRequest.getRedirectUri()
                    + " is not registered for client " + client.getClientId());
        }
    }
}
 
Example 7
/**
 * Process requested acr values if any.
 *
 * @param authorizationRequest the authorization request
 * @param principals           the principals
 */
private void processRequestedAcrValuesIfAny(final AuthorizationRequest authorizationRequest, 
                                            final List<Principal> principals) {
    if (authorizationRequest.getExtensions().containsKey(OIDCConstants.ACR_VALUES)) {
        final String[] acrValues = authorizationRequest.getExtensions()
                .get(OIDCConstants.ACR_VALUES).toString().split(" ");
        for (final String acrValue : acrValues) {
            final AuthnContextClassRefPrincipal requestedPrincipal =
                    new AuthnContextClassRefPrincipal(acrValue.trim());
            for (final AuthenticationFlowDescriptor flow : this.availableAuthenticationFlows) {
                if (!principals.contains(requestedPrincipal)
                        && flow.getSupportedPrincipals().contains(requestedPrincipal)) {
                    principals.add(requestedPrincipal);
                }
            }
        }

    }
}
 
Example 8
@RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model, Principal principal) throws Exception {
	AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest");
	ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
	model.put("auth_request", clientAuth);
	model.put("client", client);
	Map<String, String> scopes = new LinkedHashMap<String, String>();
	for (String scope : clientAuth.getScope()) {
		scopes.put(OAuth2Utils.SCOPE_PREFIX + scope, "false");  //Spring Security OAuth2 2.0.0.M2 change
	}
	for (Approval approval : approvalStore.getApprovals(principal.getName(), client.getClientId())) {
		if (clientAuth.getScope().contains(approval.getScope())) {
			scopes.put(OAuth2Utils.SCOPE_PREFIX + approval.getScope(),
					approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false");
		}
	}
	model.put("scopes", scopes);
	return new ModelAndView("access_confirmation", model);
}
 
Example 9
@RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model, HttpServletRequest request) throws Exception {
    AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");
    ModelAndView view = new ModelAndView();
    view.setViewName("authorization");
    view.addObject("clientId", authorizationRequest.getClientId());
    // 传递 scope 过去,Set 集合
    view.addObject("scopes", authorizationRequest.getScope());
    // 拼接一下名字
    view.addObject("scopeName", String.join(",", authorizationRequest.getScope()));
    return view;
}
 
Example 10
static OAuth2Authentication getOAuth2Authentication(String clientId, Set<String> scopes) {
	Authentication userAuthentication = null; // TODO no SAPUserDetails support. Using spring alternative?

	final AuthorizationRequest authorizationRequest = new AuthorizationRequest(clientId, scopes);
	authorizationRequest.setAuthorities(getAuthorities(scopes));
	authorizationRequest.setApproved(true);

	return new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication);
}
 
Example 11
@Override
public OAuth2Authentication convert(Jwt jwt) {
	AuthenticationToken authenticationToken = (AuthenticationToken) super.convert(jwt);
	String clientId = jwt.getClaimAsString(CLAIM_CLIENT_ID);
	AuthorizationRequest authorizationRequest = new AuthorizationRequest(clientId,
			authenticationToken.getAuthorities().stream().map(Objects::toString).collect(Collectors.toList()));
	authorizationRequest.setApproved(true);
	authorizationRequest.setAuthorities(authenticationToken.getAuthorities());

	return new OAuth2Authentication(authorizationRequest.createOAuth2Request(), authenticationToken);
}
 
Example 12
Source Project: Taroco   Source File: AuthorizationController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 授权页面 重写{@link WhitelabelApprovalEndpoint}
 *
 * @param model
 * @return
 */
@RequestMapping("/oauth/confirm_access")
public String authorizePage(Map<String, Object> model) {
    AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");
    final OauthClient oauthClient = oauthClientService.getById(authorizationRequest.getClientId());
    String str = "redirect:/confirm_access?clientId={}&scope={}&redirectUri={}&appName={}";
    return StrUtil.format(str,
            authorizationRequest.getClientId(),
            CollUtil.join(authorizationRequest.getScope(), StrUtil.COMMA),
            authorizationRequest.getRedirectUri(),
            oauthClient.getAppName());
}
 
Example 13
Source Project: oauth-boot   Source File: BootGrantController.java    License: MIT License 5 votes vote down vote up
@RequestMapping("/custom/confirm_access")
public String getAccessConfirmation(Map<String, Object> param, HttpServletRequest request, Model model) throws Exception {

    AuthorizationRequest authorizationRequest = (AuthorizationRequest) param.get("authorizationRequest");
    if (authorizationRequest==null){
        return "redirect:"+properties.getLoginPage();
    }
    String clientId = authorizationRequest.getClientId();
    model.addAttribute("scopes",authorizationRequest.getScope());
    Client client = this.clientService.findClientByClientId(clientId);
    model.addAttribute("client",client);

    return "base-grant";
}
 
Example 14
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
    HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
    httpSessionSecurityContextRepository.loadContext(holder);

    try {
        // 使用提供的证书认证用户
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN");
        Authentication auth = new UsernamePasswordAuthenticationToken(request.getParameter("username"), request.getParameter("password"), authorities);
        SecurityContextHolder.getContext().setAuthentication(authenticationManager.authenticate(auth));

        // 认证用户
        if(!auth.isAuthenticated())
            throw new CredentialException("用户不能够被认证");
    } catch (Exception ex) {
        // 用户不能够被认证,重定向回登录页
        logger.info(ex);
        return "login";
    }

    // 从会话得到默认保存的请求
    DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
    // 为令牌请求生成认证参数Map
    Map<String, String> authParams = getAuthParameters(defaultSavedRequest);
    AuthorizationRequest authRequest = new DefaultOAuth2RequestFactory(clientDetailsService).createAuthorizationRequest(authParams);
    authRequest.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
    model.addAttribute("authorizationRequest", authRequest);

    httpSessionSecurityContextRepository.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
    return "authorize";
}
 
Example 15
Source Project: spring-boot-demo   Source File: AuthorizationController.java    License: MIT License 5 votes vote down vote up
/**
 * 自定义确认授权页面
 * 当然你也可以使用 {@link AuthorizationEndpoint#setUserApprovalPage(String)} 方法
 * 进行设置,但是 model 就没有那么灵活了
 *
 * @param model model
 * @return ModelAndView
 */
@GetMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model) {
    AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");
    ModelAndView view = new ModelAndView();
    view.setViewName("authorization");
    view.addObject("clientId", authorizationRequest.getClientId());
    // 传递 scope 过去,Set 集合
    view.addObject("scopes", authorizationRequest.getScope());
    return view;
}
 
Example 16
Source Project: osiam   Source File: OsiamUserApprovalHandler.java    License: MIT License 5 votes vote down vote up
@Override
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest,
                                                Authentication userAuthentication) {
    ClientDetails client = osiamClientDetailsService.loadClientByClientId(authorizationRequest.getClientId());
    if (client.isAutoApprove("") || hasRememberedApprovalForClient(authorizationRequest, client)) {
        authorizationRequest.setApproved(true);
        HashMap<String, String> newApprovalParameters = new HashMap<>(authorizationRequest.getApprovalParameters());
        newApprovalParameters.put(IS_PRE_APPROVED_PARAMETER, "true");
        authorizationRequest.setApprovalParameters(Collections.unmodifiableMap(newApprovalParameters));
    }
    return authorizationRequest;
}
 
Example 17
Source Project: osiam   Source File: OsiamUserApprovalHandler.java    License: MIT License 5 votes vote down vote up
@Override
public boolean isApproved(
        AuthorizationRequest authorizationRequest, Authentication userAuthentication
) {
    boolean approved = super.isApproved(authorizationRequest, userAuthentication);

    if (!approved) {
        return false;
    }

    if ("true".equals(authorizationRequest.getApprovalParameters().get(IS_PRE_APPROVED_PARAMETER))) {
        return true;
    }

    @SuppressWarnings("unchecked")
    Map<String, Long> approvals = (Map<String, Long>) httpSession.getAttribute(APPROVALS_SESSION_KEY);
    if (approvals == null) {
        approvals = new ConcurrentHashMap<>();
        httpSession.setAttribute(APPROVALS_SESSION_KEY, approvals);
    }

    if (!approvals.containsKey(authorizationRequest.getClientId())) {
        approvals.put(authorizationRequest.getClientId(), System.currentTimeMillis());
    }

    return true;
}
 
Example 18
@Nonnull
@Override
protected Event doExecute(@Nonnull final RequestContext springRequestContext,
                          @Nonnull final ProfileRequestContext profileRequestContext) {
    log.debug("{} Building authentication context", getLogPrefix());
    final AuthenticationContext ac = new AuthenticationContext();
    
    final OIDCAuthorizationRequestContext authZContext =
            profileRequestContext.getSubcontext(OIDCAuthorizationRequestContext.class);
    if (authZContext == null) {
        log.warn("No authorization request could be located in the profile request context");
        return Events.Failure.event(this);
    }

    final AuthorizationRequest authorizationRequest = authZContext.getAuthorizationRequest();
    if (authorizationRequest == null || Strings.isNullOrEmpty(authorizationRequest.getClientId())) {
        log.warn("Authorization request could not be loaded from session");
        return Events.Failure.event(this);
    }

    ac.setForceAuthn(authZContext.isForceAuthentication());
    if (ac.isForceAuthn()) {
        log.debug("Authentication context requires force authN for {}",
                authorizationRequest.getClientId());
    } else {
        log.debug("Authentication context does not require force authN for {}",
                authorizationRequest.getClientId());
    }

    final List<Principal> principals = new ArrayList<>();
    processRequestedAcrValuesIfAny(authorizationRequest, principals);
    processAcrValuesBasedOnPrincipalWeightMap(principals);
    addRequestedPrincipalIntoContext(ac, principals);
    
    profileRequestContext.addSubcontext(ac, true);
    profileRequestContext.setBrowserProfile(true);
    return Events.Success.event(this);
}
 
Example 19
@Nonnull
@Override
protected Event doExecute(@Nonnull final RequestContext springRequestContext,
                          @Nonnull final ProfileRequestContext profileRequestContext) {

    final OIDCAuthorizationRequestContext authZContext = 
            profileRequestContext.getSubcontext(OIDCAuthorizationRequestContext.class);
    if (authZContext == null) {
        log.warn("No authorization request could be located in the profile request context");
        return Events.Failure.event(this);
    }

    final AuthorizationRequest authRequest = authZContext.getAuthorizationRequest();
    if (authRequest == null || Strings.isNullOrEmpty(authRequest.getClientId())) {
        log.warn("Authorization request could not be loaded from session");
        return Events.Failure.event(this);
    }

    final ClientDetailsEntity client = this.clientService.loadClientByClientId(authRequest.getClientId());

    if (client == null) {
        log.warn("Client configuration could not be loaded from session");
        return Events.Failure.event(this);
    }
    final RelyingPartyContext rpc = new RelyingPartyContext();

    rpc.setVerified(true);
    rpc.setRelyingPartyId(client.getClientId());
    log.debug("{} Setting up RP context for verified relying party {}",
            getLogPrefix(), client.getClientId());
    profileRequestContext.addSubcontext(rpc);
    return Events.Success.event(this);
}
 
Example 20
/**
 * Build open id connect response.
 *
 * @param authRequest the auth request
 * @param client      the client
 * @return the open id connect response
 */
private OIDCResponse buildOpenIdConnectResponse(final AuthorizationRequest authRequest,
                                                final ClientDetailsEntity client) {
    final OIDCResponse response = new OIDCResponse();
    response.setAuthorizationRequest(authRequest);
    response.setClient(client);
    response.setRedirectUri(authRequest.getRedirectUri());

    log.debug("Built initial response for client {} and redirect uri {}",
        client, authRequest.getRedirectUri());

    // pre-process the scopes
    final Set<SystemScope> scopes = scopeService.fromStrings(authRequest.getScope());
    log.debug("System scopes retrieved based on the authorization request scope {} are {}",
        authRequest.getScope(), scopes);

    final Set<SystemScope> sortedScopes = getSystemScopes(scopes);
    response.setScopes(sortedScopes);
    log.debug("Response will contain the following scopes {}", sortedScopes);

    final Map<String, Map<String, String>> claimsForScopes = getUserInfoClaimsForScopes(sortedScopes, client);
    response.setClaims(claimsForScopes);
    log.debug("Response will contain the following claims for scopes {}", claimsForScopes.keySet());

    // client stats
    final Integer count = statsService.getCountForClientId(client.getClientId()).getApprovedSiteCount();
    response.setCount(count);

    if (client.getContacts() != null) {
        response.setContacts(client.getContacts());
    }

    // if the client is over a week old and has more than one registration, don't give such a big warning
    // instead, tag as "Generally Recognized As Safe" (gras)
    final Date lastWeek = new Date(System.currentTimeMillis() - (60 * 60 * 24 * 7 * 1000));
    response.setGras(count > 1 && client.getCreatedAt() != null && client.getCreatedAt().before(lastWeek));
    return response;
}
 
Example 21
@Override
public AuthorizationRequest createAuthorizationRequest(final Map<String, String> inputParams) {
    final AuthorizationRequest request = super.createAuthorizationRequest(inputParams);
    if (inputParams.containsKey(OIDCConstants.ACR_VALUES)) {
        try {
            log.debug("Authorization request contains {}. Decoding and storing values into the request", 
                    OIDCConstants.ACR_VALUES);
            request.getExtensions().put(OIDCConstants.ACR_VALUES,
                    URLDecoder.decode(inputParams.get(OIDCConstants.ACR_VALUES), "UTF-8"));
        } catch (final Exception e) {
            log.warn("Unable to decode acr_values in the authorization request", e);
        }
    }
    return request;
}
 
Example 22
public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
    if (super.isApproved(authorizationRequest, userAuthentication)) {
        return true;
    }
    if (!userAuthentication.isAuthenticated()) {
        return false;
    }

    OauthClientDetails clientDetails = oauthService.loadOauthClientDetails(authorizationRequest.getClientId());
    return clientDetails != null && clientDetails.trusted();

}
 
Example 23
/**
 * Allows automatic approval for a white list of clients in the implicit grant case.
 * 
 * @param authorizationRequest The authorization request.
 * @param userAuthentication the current user authentication
 * 
 * @return An updated request if it has already been approved by the current user.
 */
@Override
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest,
		Authentication userAuthentication) {

	boolean approved = false;
	// If we are allowed to check existing approvals this will short circuit the decision
	if (useApprovalStore) {
		authorizationRequest = super.checkForPreApproval(authorizationRequest, userAuthentication);
		approved = authorizationRequest.isApproved();
	}
	else {
		if (clientDetailsService != null) {
			Collection<String> requestedScopes = authorizationRequest.getScope();
			try {
				ClientDetails client = clientDetailsService
						.loadClientByClientId(authorizationRequest.getClientId());
				for (String scope : requestedScopes) {
					if (client.isAutoApprove(scope) || client.isAutoApprove("all")) {
						approved = true;
						break;
					}
				}
			}
			catch (ClientRegistrationException e) {
			}
		}
	}
	authorizationRequest.setApproved(approved);

	return authorizationRequest;
}
 
Example 24
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {

    HttpRequestResponseHolder responseHolder = new HttpRequestResponseHolder(request, response);
    sessionRepository.loadContext(responseHolder);

    try {
        // Authenticate the user with the supplied credentials
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN");

        Authentication auth =
                new UsernamePasswordAuthenticationToken(request.getParameter("username"),
                        request.getParameter("password"), authorities);

        SecurityContextHolder.getContext()
                .setAuthentication(authenticationManager.authenticate(auth));

        // Authenticate the user
        if(!authenticationManager.authenticate(auth).isAuthenticated())
            throw new CredentialException("User could not be authenticated");

    } catch (Exception ex) {
        // The user couldn't be authenticated, redirect back to login
        ex.printStackTrace();
        return "login";
    }

    // Get the default saved request from session
    DefaultSavedRequest defaultSavedRequest = ((DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST"));

    // Generate an authorization parameter map for the token request
    Map<String, String> authParams = getAuthParameters(defaultSavedRequest);

    // Create the authorization request and put it in the view model
    AuthorizationRequest authRequest = new DefaultOAuth2RequestFactory(clients).createAuthorizationRequest(authParams);
    authRequest.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
    sessionRepository.saveContext(SecurityContextHolder.getContext(), responseHolder.getRequest(), responseHolder.getResponse());
    model.addAttribute("authorizationRequest", authRequest);

    // Return the token authorization view
    return "authorize";
}
 
Example 25
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {

    HttpRequestResponseHolder responseHolder = new HttpRequestResponseHolder(request, response);
    sessionRepository.loadContext(responseHolder);

    try {
        // Authenticate the user with the supplied credentials
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN");

        Authentication auth =
                new UsernamePasswordAuthenticationToken(request.getParameter("username"),
                        request.getParameter("password"), authorities);

        SecurityContextHolder.getContext()
                .setAuthentication(authenticationManager.authenticate(auth));

        // Authenticate the user
        if(!authenticationManager.authenticate(auth).isAuthenticated())
            throw new CredentialException("User could not be authenticated");

    } catch (Exception ex) {
        // The user couldn't be authenticated, redirect back to login
        ex.printStackTrace();
        return "login";
    }

    // Get the default saved request from session
    DefaultSavedRequest defaultSavedRequest = ((DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST"));

    // Generate an authorization parameter map for the token request
    Map<String, String> authParams = getAuthParameters(defaultSavedRequest);

    // Create the authorization request and put it in the view model
    AuthorizationRequest authRequest = new DefaultOAuth2RequestFactory(clients).createAuthorizationRequest(authParams);
    authRequest.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
    sessionRepository.saveContext(SecurityContextHolder.getContext(), responseHolder.getRequest(), responseHolder.getResponse());
    model.addAttribute("authorizationRequest", authRequest);

    // Return the token authorization view
    return "authorize";
}
 
Example 26
@Nonnull
@Override
protected Event doExecute(@Nonnull final RequestContext springRequestContext,
                          @Nonnull final ProfileRequestContext profileRequestContext) {
    final HttpServletRequest request = OIDCUtils.getHttpServletRequest(springRequestContext);
    if (request == null) {
        throw new OIDCException("HttpServletRequest cannot be null");
    }

    final HttpServletResponse response = OIDCUtils.getHttpServletResponse(springRequestContext);
    if (response == null) {
        throw new OIDCException("HttpServletRequest cannot be null");
    }

    final AuthorizationRequest authorizationRequest = createAuthorizationRequest(request);
    if (Strings.isNullOrEmpty(authorizationRequest.getClientId())) {
        throw new OIDCException("No client id is specified in the authorization request");
    }


    final OIDCAuthorizationRequestContext authZContext = new OIDCAuthorizationRequestContext();
    authZContext.setAuthorizationRequest(authorizationRequest);

    if (authZContext.isImplicitResponseType() && Strings.isNullOrEmpty(authZContext.getNonce())) {
        log.error("nonce is required since the requesting flow is implicit");
        throw new OIDCException("nonce is required when handling implicit response type");
    }
    
    final ClientDetailsEntity client = loadClientObject(authZContext);
    ensureRedirectUriIsAuthorized(authorizationRequest, client);
    
    log.debug("Found client {}.", client.getClientId());
    
    processLoginHintParameterIfNeeded(request, authZContext);

    Pair<Events, ? extends Object> pairEvent = new Pair<>(Events.Success, null);
    final String prompt = (String) authorizationRequest.getExtensions().get(ConnectRequestParameters.PROMPT);
    if (prompt != null) {
        log.debug("Authorization request contains prompt {}", prompt);
        pairEvent = checkForPrompts(prompt, request, client, authZContext);
    }

    return produceFinalEvent(profileRequestContext, response, authZContext, 
            pairEvent, springRequestContext, client);
}
 
Example 27
@Nonnull
@Override
protected Event doExecute(@Nonnull final RequestContext springRequestContext,
                          @Nonnull final ProfileRequestContext profileRequestContext) {

    final OIDCAuthorizationRequestContext authZContext =
        profileRequestContext.getSubcontext(OIDCAuthorizationRequestContext.class);
    if (authZContext == null) {
        log.warn("No authorization request could be located in the profile request context");
        return Events.Failure.event(this);
    }

    final AuthorizationRequest authRequest = authZContext.getAuthorizationRequest();
    if (authRequest == null || Strings.isNullOrEmpty(authRequest.getClientId())) {
        log.warn("Authorization request could not be loaded from session");
        return Events.Failure.event(this);
    }

    /*
    final String prompt = (String)authRequest.getExtensions().get(ConnectRequestParameters.PROMPT);
    final List<String> prompts = Splitter.on(ConnectRequestParameters.PROMPT_SEPARATOR)
            .splitToList(Strings.nullToEmpty(prompt));
    */

    final ClientDetailsEntity client;

    try {
        client = clientService.loadClientByClientId(authRequest.getClientId());
        if (client == null) {
            log.error("Could not find client {}", authRequest.getClientId());
            return Events.ClientNotFound.event(this);
        }
    } catch (final Exception e) {
        log.error(e.getMessage(), e);
        return Events.BadRequest.event(this);
    }

    /*
    if (prompts.contains(ConnectRequestParameters.PROMPT_NONE)) {
        log.debug("Handling authorization when prompt contains none");
        return handleWhenNoPromptIsPresent(springRequestContext, request, authRequest, client);
    }
    */

    final Authentication authentication =
        SpringSecurityAuthenticationTokenFactory.buildAuthentication(profileRequestContext, client);
    storeSpringSecurityAuthenticationContext(profileRequestContext, springRequestContext, authentication);
    storeAuthenticationTimeIntoAuthorizationRequest(authentication, authRequest);
    final OIDCResponse response = buildOpenIdConnectResponse(authRequest, client);
    final OIDCAuthorizationResponseContext responseContext = new OIDCAuthorizationResponseContext();
    responseContext.setOidcResponse(response);
    profileRequestContext.addSubcontext(responseContext);
    return Events.Proceed.event(this);
}
 
Example 28
Source Project: shibboleth-oidc   Source File: OIDCResponse.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Gets authorization request.
 *
 * @return the authorization request
 */
public AuthorizationRequest getAuthorizationRequest() {
    return authorizationRequest;
}
 
Example 29
Source Project: shibboleth-oidc   Source File: OIDCResponse.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Sets authorization request.
 *
 * @param authZRequest the authorization request
 */
public void setAuthorizationRequest(final AuthorizationRequest authZRequest) {
    this.authorizationRequest = authZRequest;
}
 
Example 30
/**
 * Create authorization request authorization request.
 *
 * @param request the request
 * @return the authorization request
 */
private AuthorizationRequest createAuthorizationRequest(final HttpServletRequest request) {
    log.debug("Constructing authorization request");
    final Map<String, String> requestParameters = createRequestMap(request.getParameterMap());
    return authRequestFactory.createAuthorizationRequest(requestParameters);
}