Search in sources :

Example 1 with Apps

use of org.maxkey.entity.apps.Apps in project MaxKey by dromara.

the class AuthorizationEndpoint method authorize.

@Operation(summary = "OAuth 2.0 认证接口", description = "传递参数client_id,response_type,redirect_uri等", method = "GET")
@RequestMapping(value = { OAuth2Constants.ENDPOINT.ENDPOINT_AUTHORIZE, OAuth2Constants.ENDPOINT.ENDPOINT_TENCENT_IOA_AUTHORIZE }, method = RequestMethod.GET)
public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters, SessionStatus sessionStatus) {
    Principal principal = (Principal) WebContext.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.
    AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters);
    Set<String> responseTypes = authorizationRequest.getResponseTypes();
    if (!responseTypes.contains(OAuth2Constants.PARAMETER.TOKEN) && !responseTypes.contains(OAuth2Constants.PARAMETER.CODE)) {
        throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
    }
    if (authorizationRequest.getClientId() == null) {
        throw new InvalidClientException("A client id must be provided");
    }
    try {
        if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) {
            throw new InsufficientAuthenticationException("User must be authenticated with Spring Security before authorization can be completed.");
        }
        ClientDetails client = getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId(), true);
        // The resolved redirect URI is either the redirect_uri from the parameters or the one from
        // clientDetails. Either way we need to store it on the AuthorizationRequest.
        String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Constants.PARAMETER.REDIRECT_URI);
        String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
        if (!StringUtils.hasText(resolvedRedirect)) {
            logger.info("Client redirectUri " + resolvedRedirect);
            logger.info("Parameter redirectUri " + redirectUriParameter);
            throw new RedirectMismatchException("A redirectUri must be either supplied or preconfigured in the ClientDetails");
        }
        authorizationRequest.setRedirectUri(resolvedRedirect);
        // We intentionally only validate the parameters requested by the client (ignoring any data that may have
        // been added to the request by the manager).
        oauth2RequestValidator.validateScope(authorizationRequest, client);
        // Some systems may allow for approval decisions to be remembered or approved by default. Check for
        // such logic here, and set the approved flag on the authorization request accordingly.
        authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, (Authentication) principal);
        // is this call necessary?
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);
        // Validation is all done, so we can check for auto approval...
        if (authorizationRequest.isApproved()) {
            if (responseTypes.contains(OAuth2Constants.PARAMETER.TOKEN)) {
                return getImplicitGrantResponse(authorizationRequest);
            }
            if (responseTypes.contains(OAuth2Constants.PARAMETER.CODE)) {
                return new ModelAndView(getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal));
            }
        }
        Apps app = (Apps) WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP);
        // session中为空或者id不一致重新加载
        if (app == null || !app.getId().equalsIgnoreCase(authorizationRequest.getClientId())) {
            app = appsService.get(authorizationRequest.getClientId());
            WebContext.setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP, app);
        }
        // Place auth request into the model so that it is stored in the session
        // for approveOrDeny to use. That way we make sure that auth request comes from the session,
        // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session.
        model.put("authorizationRequest", authorizationRequest);
        return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal);
    } catch (RuntimeException e) {
        sessionStatus.setComplete();
        throw e;
    }
}
Also used : AuthorizationRequest(org.maxkey.authz.oauth2.provider.AuthorizationRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) Apps(org.maxkey.entity.apps.Apps) ClientDetails(org.maxkey.entity.apps.oauth2.provider.ClientDetails) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.maxkey.authz.oauth2.provider.OAuth2Authentication) InvalidClientException(org.maxkey.authz.oauth2.common.exceptions.InvalidClientException) RedirectMismatchException(org.maxkey.authz.oauth2.common.exceptions.RedirectMismatchException) UnsupportedResponseTypeException(org.maxkey.authz.oauth2.common.exceptions.UnsupportedResponseTypeException) Principal(java.security.Principal) Operation(io.swagger.v3.oas.annotations.Operation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with Apps

use of org.maxkey.entity.apps.Apps in project MaxKey by dromara.

the class OAuth20AccessConfirmationEndpoint method getAccessConfirmation.

/**
 * getAccessConfirmation.
 * @param model  Map
 * @return
 * throws Exception
 */
@RequestMapping(OAuth2Constants.ENDPOINT.ENDPOINT_APPROVAL_CONFIRM)
public ModelAndView getAccessConfirmation(@RequestParam Map<String, Object> model) {
    try {
        model.remove("authorizationRequest");
        // Map<String, Object> model
        AuthorizationRequest clientAuth = (AuthorizationRequest) WebContext.getAttribute("authorizationRequest");
        ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId(), true);
        Apps app = (Apps) WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP);
        WebContext.setAttribute(app.getId(), app.getIcon());
        model.put("auth_request", clientAuth);
        model.put("client", client);
        model.put("app", app);
        model.put("oauth_version", "oauth 2.0");
        Map<String, String> scopes = new LinkedHashMap<String, String>();
        for (String scope : clientAuth.getScope()) {
            scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + scope, "false");
        }
        String principal = ((SigninPrincipal) WebContext.getAuthentication().getPrincipal()).getUsername();
        for (Approval approval : approvalStore.getApprovals(principal, client.getClientId())) {
            if (clientAuth.getScope().contains(approval.getScope())) {
                scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + approval.getScope(), approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false");
            }
        }
        model.put("scopes", scopes);
        if (!model.containsKey(OAuth2Constants.PARAMETER.APPROVAL_PROMPT)) {
            model.put(OAuth2Constants.PARAMETER.APPROVAL_PROMPT, client.getApprovalPrompt());
        }
    } catch (Exception e) {
        _logger.debug("OAuth Access Confirmation process error.", e);
    }
    ModelAndView modelAndView = new ModelAndView("authorize/oauth_access_confirmation");
    _logger.trace("Confirmation details ");
    for (Object key : model.keySet()) {
        _logger.trace("key " + key + "=" + model.get(key));
    }
    modelAndView.addObject("model", model);
    return modelAndView;
}
Also used : AuthorizationRequest(org.maxkey.authz.oauth2.provider.AuthorizationRequest) ClientDetails(org.maxkey.entity.apps.oauth2.provider.ClientDetails) SigninPrincipal(org.maxkey.authn.SigninPrincipal) ModelAndView(org.springframework.web.servlet.ModelAndView) Approval(org.maxkey.authz.oauth2.provider.approval.Approval) Apps(org.maxkey.entity.apps.Apps) LinkedHashMap(java.util.LinkedHashMap) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 with Apps

use of org.maxkey.entity.apps.Apps in project MaxKey by dromara.

the class AppListController method appUserConfig.

@ResponseBody
@RequestMapping(value = { "/appUserConfig" })
public Message appUserConfig(@RequestParam("protocol") String protocol, @RequestParam("credential") int credential, @RequestParam("appId") String appId, @RequestParam("identity_username") String identity_username, @RequestParam("identity_password") String identity_password) {
    Apps app = appsService.get(appId);
    UserInfo userInfo = WebContext.getUserInfo();
    Accounts appUsers = new Accounts();
    appUsers.setAppId(appId);
    appUsers.setUserId(userInfo.getId());
    if (identity_password != null && !identity_password.equals("") && credential == Apps.CREDENTIALS.USER_DEFINED) {
        appUsers = appUsersService.load(new Accounts(userInfo.getId(), appId));
        if (appUsers == null) {
            appUsers = new Accounts();
            appUsers.setId(appUsers.generateId());
            appUsers.setAppId(appId);
            appUsers.setAppName(app.getName());
            appUsers.setUserId(userInfo.getId());
            appUsers.setUsername(userInfo.getUsername());
            appUsers.setDisplayName(userInfo.getDisplayName());
            appUsers.setRelatedUsername(identity_username);
            appUsers.setRelatedPassword(PasswordReciprocal.getInstance().encode(identity_password));
            appUsers.setInstId(userInfo.getInstId());
            appUsers.setStatus(ConstsStatus.ACTIVE);
            appUsersService.insert(appUsers);
        } else {
            appUsers.setRelatedUsername(identity_username);
            appUsers.setRelatedPassword(PasswordReciprocal.getInstance().encode(identity_password));
            appUsersService.update(appUsers);
        }
    }
    return new Message(WebContext.getI18nValue(ConstsOperateMessage.UPDATE_SUCCESS), MessageType.success);
}
Also used : ConstsOperateMessage(org.maxkey.constants.ConstsOperateMessage) Message(org.maxkey.web.message.Message) UserInfo(org.maxkey.entity.UserInfo) UserApps(org.maxkey.entity.apps.UserApps) Apps(org.maxkey.entity.apps.Apps) Accounts(org.maxkey.entity.Accounts) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with Apps

use of org.maxkey.entity.apps.Apps in project MaxKey by dromara.

the class ApplicationsController method queryDataGrid.

@RequestMapping(value = { "/grid" })
@ResponseBody
public JpaPageResults<Apps> queryDataGrid(@ModelAttribute("applications") Apps applications) {
    applications.setInstId(WebContext.getUserInfo().getInstId());
    JpaPageResults<Apps> apps = appsService.queryPageResults(applications);
    if (apps != null && apps.getRows() != null) {
        for (Apps app : apps.getRows()) {
            app.transIconBase64();
        }
    }
    return apps;
}
Also used : Apps(org.maxkey.entity.apps.Apps) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 5 with Apps

use of org.maxkey.entity.apps.Apps in project MaxKey by dromara.

the class ExtendApiDetailsController method forwardUpdate.

@RequestMapping(value = { "/forwardUpdate/{id}" })
public ModelAndView forwardUpdate(@PathVariable("id") String id) {
    ModelAndView modelAndView = new ModelAndView("apps/extendapi/appUpdate");
    Apps application = appsService.get(id);
    super.decoderSecret(application);
    AppsExtendApiDetails extendApiDetails = new AppsExtendApiDetails();
    BeanUtils.copyProperties(application, extendApiDetails);
    extendApiDetails.transIconBase64();
    modelAndView.addObject("model", extendApiDetails);
    return modelAndView;
}
Also used : ModelAndView(org.springframework.web.servlet.ModelAndView) AppsExtendApiDetails(org.maxkey.entity.apps.AppsExtendApiDetails) Apps(org.maxkey.entity.apps.Apps) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

Apps (org.maxkey.entity.apps.Apps)28 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)16 ModelAndView (org.springframework.web.servlet.ModelAndView)13 Operation (io.swagger.v3.oas.annotations.Operation)7 AbstractAuthorizeAdapter (org.maxkey.authz.endpoint.adapter.AbstractAuthorizeAdapter)5 ExtraAttrs (org.maxkey.entity.ExtraAttrs)5 Accounts (org.maxkey.entity.Accounts)4 UserInfo (org.maxkey.entity.UserInfo)4 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)4 ClientDetails (org.maxkey.entity.apps.oauth2.provider.ClientDetails)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 HashMap (java.util.HashMap)2 Cookie (javax.servlet.http.Cookie)2 SigninPrincipal (org.maxkey.authn.SigninPrincipal)2 AuthorizationRequest (org.maxkey.authz.oauth2.provider.AuthorizationRequest)2 OAuth2Authentication (org.maxkey.authz.oauth2.provider.OAuth2Authentication)2 GroupPrivileges (org.maxkey.entity.GroupPrivileges)2 HistoryLoginApps (org.maxkey.entity.HistoryLoginApps)2 UserApps (org.maxkey.entity.apps.UserApps)2 HttpRequestAdapter (org.maxkey.web.HttpRequestAdapter)2