Search in sources :

Example 26 with OAuth

use of org.apache.oltu.oauth2.common.OAuth in project dq-easy-cloud by dq-open-cloud.

the class EcAuthorizeController method authorize.

@RequestMapping("/toAuthorize")
public Object authorize(Model model, HttpServletRequest request) throws URISyntaxException, OAuthSystemException {
    // http://localhost:8100/authorize/toAuthorize?redirect_uri=https://www.baidu.com/&response_type=code&client_id=1&state=bb38108d1aaf567c72da0f1167e87142d0e20cb2bb24ec5a
    try {
        // 构建OAuth 授权请求
        OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);
        boolean checkClient = false;
        // 检查传入的客户端id是否正确
        if (checkClient) {
            OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).setError(OAuthError.TokenResponse.INVALID_CLIENT).setErrorDescription("非法用户").buildJSONMessage();
            return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
        }
        Subject subject = SecurityUtils.getSubject();
        // 如果用户没有登录,跳转到登陆页面
        if (!subject.isAuthenticated()) {
            if (!login(subject, request)) {
                // model.addAttribute("client", clientService.findByClientId(oauthRequest.getClientId()));
                return "oauth2login";
            }
        }
        String username = (String) subject.getPrincipal();
        // 生成授权码
        String authorizationCode = null;
        // responseType目前仅支持CODE,另外还有TOKEN
        String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
        if (responseType.equals(ResponseType.CODE.toString())) {
            OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
            authorizationCode = oauthIssuerImpl.authorizationCode();
            codeCache.put(authorizationCode, "zhangsan");
        // oAuthService.addAuthCode(authorizationCode, username);
        }
        // 进行OAuth响应构建
        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
        // 设置授权码
        builder.setCode(authorizationCode);
        // 得到到客户端重定向地址
        String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
        // 构建响应
        final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();
        // 根据OAuthResponse返回ResponseEntity响应
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
    } catch (OAuthProblemException e) {
        logger.error(e.getMessage(), e);
        // 出错处理
        String redirectUri = e.getRedirectUri();
        if (OAuthUtils.isEmpty(redirectUri)) {
            // 告诉客户端没有传入redirectUri直接报错
            return new ResponseEntity("OAuth callback url needs to be provided by client!!!", HttpStatus.NOT_FOUND);
        }
        // 返回错误消息(如?error=)
        final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e).location(redirectUri).buildQueryMessage();
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) URI(java.net.URI) Subject(org.apache.shiro.subject.Subject) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthIssuerImpl(org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl) ResponseEntity(org.springframework.http.ResponseEntity) OAuthAuthzRequest(org.apache.oltu.oauth2.as.request.OAuthAuthzRequest) MD5Generator(org.apache.oltu.oauth2.as.issuer.MD5Generator) OAuthASResponse(org.apache.oltu.oauth2.as.response.OAuthASResponse) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 27 with OAuth

use of org.apache.oltu.oauth2.common.OAuth in project dq-easy-cloud by dq-open-cloud.

the class EcAuthorizeController method userInfo.

@RequestMapping("/userInfo")
public HttpEntity userInfo(HttpServletRequest request) throws OAuthSystemException {
    try {
        // 构建OAuth资源请求
        OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request, ParameterStyle.QUERY);
        // 获取Access Token
        String accessToken = oauthRequest.getAccessToken();
        // 验证Access Token
        boolean accessTokenFlag = false;
        // if (!oAuthService.checkAccessToken(accessToken)) {
        if (accessTokenFlag) {
            // 如果不存在/过期了,返回未验证错误,需重新验证
            OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED).setRealm("过期了").setError(OAuthError.ResourceResponse.INVALID_TOKEN).buildHeaderMessage();
            HttpHeaders headers = new HttpHeaders();
            headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
            return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
        }
        // 返回用户名
        // String username = oAuthService.getUsernameByAccessToken(accessToken);
        Object username = tokenCache.get(accessToken);
        return new ResponseEntity(username, HttpStatus.OK);
    } catch (OAuthProblemException e) {
        // 检查是否设置了错误码
        String errorCode = e.getError();
        if (OAuthUtils.isEmpty(errorCode)) {
            OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED).setRealm("server").buildHeaderMessage();
            HttpHeaders headers = new HttpHeaders();
            headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
            return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
        }
        OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED).setRealm("server").setError(e.getError()).setErrorDescription(e.getDescription()).setErrorUri(e.getUri()).buildHeaderMessage();
        HttpHeaders headers = new HttpHeaders();
        headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
        return new ResponseEntity(HttpStatus.BAD_REQUEST);
    }
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) OAuthAccessResourceRequest(org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 28 with OAuth

use of org.apache.oltu.oauth2.common.OAuth in project java-demos by powerLeePlus.

the class AuthorizationController method authorize.

@RequestMapping("/authorize")
public Object authorize(Model model, HttpServletRequest request) throws OAuthSystemException, URISyntaxException {
    try {
        // 构建OAuth 授权请求
        OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);
        // 根据传入的clientId 判断 客户端是否存在
        if (!authorizationService.checkClientId(oauthRequest.getClientId())) {
            // 生成错误信息,告知客户端不存在
            OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).setError(OAuthError.TokenResponse.INVALID_CLIENT).setErrorDescription("客户端验证失败,如错误的client_id/client_secret").buildJSONMessage();
            return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
        }
        // 判断用户是否登录
        Subject subject = SecurityUtils.getSubject();
        // 如果用户没有登录,跳转到登录页面
        if (!subject.isAuthenticated()) {
            if (!login(subject, request)) {
                // 登录失败时跳转到登陆授权页页面
                return "/oauth2";
            }
        }
        String username = ((User) subject.getPrincipal()).getUsername();
        // 生成授权码
        String authorizationCode = null;
        String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
        if (responseType.equals(ResponseType.CODE.toString())) {
            OAuthIssuerImpl oAuthIssuer = new OAuthIssuerImpl(new MD5Generator());
            authorizationCode = oAuthIssuer.authorizationCode();
            // 把授权码放到缓存中
            authorizationService.addAuthCode(authorizationCode, username);
        }
        // 进行OAuth响应构建
        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
        // 设置授权码
        builder.setCode(authorizationCode);
        // 根据客户端重定向地址
        String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
        // 构建响应
        final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();
        // 根据OAuthResponse 返回 ResponseEntity响应
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
    } catch (OAuthProblemException e) {
        // 出错处理
        String redirectUri = e.getRedirectUri();
        if (OAuthUtils.isEmpty(redirectUri)) {
            // 告诉客户端没有传入redirectUri直接报错
            return new ResponseEntity("告诉客户端没有传入redirectUri直接报错!", HttpStatus.NOT_FOUND);
        }
        // 这是服务端的一次重定向
        final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e).location(redirectUri).buildQueryMessage();
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) User(org.lwq.oauth2.server.pojo.User) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) URI(java.net.URI) Subject(org.apache.shiro.subject.Subject) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthIssuerImpl(org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl) ResponseEntity(org.springframework.http.ResponseEntity) OAuthAuthzRequest(org.apache.oltu.oauth2.as.request.OAuthAuthzRequest) MD5Generator(org.apache.oltu.oauth2.as.issuer.MD5Generator) OAuthASResponse(org.apache.oltu.oauth2.as.response.OAuthASResponse) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 29 with OAuth

use of org.apache.oltu.oauth2.common.OAuth in project java-demos by powerLeePlus.

the class UserInfoController method userInfo.

@RequestMapping("/userInfo")
public HttpEntity userInfo(HttpServletRequest request) throws OAuthSystemException {
    try {
        // 构建OAuth资源请求
        OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request, ParameterStyle.QUERY);
        // 获取Access Token
        String accessToken = oauthRequest.getAccessToken();
        // 验证Access Token
        if (!authorizationService.checkAccessToken(accessToken)) {
            // 如果不存在/过期了,返回未验证错误,需重新验证
            OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED).setRealm("oauth-server").setError(OAuthError.ResourceResponse.INVALID_TOKEN).buildHeaderMessage();
            HttpHeaders headers = new HttpHeaders();
            headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
            return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
        }
        // 返回用户名
        String username = authorizationService.getUsernameByAccessToken(accessToken);
        return new ResponseEntity(username, HttpStatus.OK);
    } catch (OAuthProblemException e) {
        // 检查是否设置了错误码
        String errorCode = e.getError();
        if (OAuthUtils.isEmpty(errorCode)) {
            OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED).setRealm("fxb").buildHeaderMessage();
            HttpHeaders headers = new HttpHeaders();
            headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
            return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
        }
        OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED).setRealm("oauth-server").setError(e.getError()).setErrorDescription(e.getDescription()).setErrorUri(e.getUri()).buildHeaderMessage();
        HttpHeaders headers = new HttpHeaders();
        headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
        return new ResponseEntity(HttpStatus.BAD_REQUEST);
    }
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) OAuthAccessResourceRequest(org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 30 with OAuth

use of org.apache.oltu.oauth2.common.OAuth in project openhab-addons by openhab.

the class NetatmoBridgeHandler method initializeApiClient.

private void initializeApiClient() {
    try {
        ApiClient apiClient = new ApiClient();
        OAuthClientRequest oAuthRequest = OAuthClientRequest.tokenLocation("https://api.netatmo.net/oauth2/token").setClientId(configuration.clientId).setClientSecret(configuration.clientSecret).setUsername(configuration.username).setPassword(configuration.password).setScope(getApiScope()).setGrantType(GrantType.PASSWORD).buildBodyMessage();
        OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
        OAuthJSONAccessTokenResponse accessTokenResponse = oAuthClient.accessToken(oAuthRequest, OAuthJSONAccessTokenResponse.class);
        String accessToken = accessTokenResponse.getAccessToken();
        for (Authentication authentication : apiClient.getAuthentications().values()) {
            if (authentication instanceof OAuth) {
                ((OAuth) authentication).setAccessToken(accessToken);
            }
        }
        apiCreator = new APICreator(apiClient);
    } catch (OAuthSystemException | OAuthProblemException e) {
        throw new RuntimeException("Error on trying to get an access token!", e);
    }
}
Also used : OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) ApiClient(io.swagger.client.ApiClient) OAuth(io.swagger.client.auth.OAuth) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) Authentication(io.swagger.client.auth.Authentication) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)22 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)17 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)14 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)11 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)10 URI (java.net.URI)9 HashMap (java.util.HashMap)7 OAuthIssuerImpl (org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl)6 OAuthASResponse (org.apache.oltu.oauth2.as.response.OAuthASResponse)6 ResponseEntity (org.springframework.http.ResponseEntity)6 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)6 MD5Generator (org.apache.oltu.oauth2.as.issuer.MD5Generator)5 OAuthAuthzRequest (org.apache.oltu.oauth2.as.request.OAuthAuthzRequest)5 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 OAuthAuthzResponse (org.apache.oltu.oauth2.client.response.OAuthAuthzResponse)4 HttpHeaders (org.springframework.http.HttpHeaders)4 ServletException (javax.servlet.ServletException)3