标签: spring-oauth2

spring boot OAuth2基于角色的授权

我们有一个扩展AuthorizationServerConfigurerAdapter的专用授权服务器,我们在其中设置了覆盖void configure(ClientDetailsS​​erviceConfigurer clients)方法的权限.

    @Configuration
    @EnableAuthorizationServer
    protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Value('${oauth.clientId}')
    private String clientId

    @Value('${oauth.secret:}')
    private String secret

    @Value('${oauth.resourceId}')
    private String resourceId

    @Autowired
    @Qualifier('authenticationManagerBean')
    private AuthenticationManager authenticationManager

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        return new JwtAccessTokenConverter();
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.checkTokenAccess("permitAll()")
        oauthServer.allowFormAuthenticationForClients()
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .accessTokenConverter(accessTokenConverter())
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient(clientId)
                .secret(secret)
                .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
                .authorities("USER", "ADMIN")
                .scopes("read", "write", "trust") …
Run Code Online (Sandbox Code Playgroud)

oauth-2.0 spring-boot spring-security-oauth2 spring-oauth2

7
推荐指数
1
解决办法
7041
查看次数

如何自动装配这个TokenStore

如何触发此示例Spring Boot OAuth2应用程序的自动注销?

我尝试将以下代码从另一个帖子的答案中添加到应用程序demo包中的新控制器类中: authserver

package demo;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;

@Controller
public class OAuthController {
    @Autowired
    private TokenStore tokenStore;

    @RequestMapping(value = "/oauth/revoke-token", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public void logout(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null) {
            String tokenValue = authHeader.replace("Bearer", "").trim();
            OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
            tokenStore.removeAccessToken(accessToken);
        }
    }
}  
Run Code Online (Sandbox Code Playgroud)

但是当我尝试启动应用程序时,调试日志会显示以下错误,指示它不能autowire存储令牌存储:

Caused by: org.springframework.beans.factory.BeanCreationException: …
Run Code Online (Sandbox Code Playgroud)

spring spring-security autowired spring-boot spring-oauth2

7
推荐指数
1
解决办法
1万
查看次数

请求'OPTIONS/logout'与'POST/logout'不匹配

我正在通过分解此GitHub示例中的三个互连应用程序来学习Spring Cloud和Spring OAuth2 .当我打开了/oauth/revoke-token在终端authserver应用程序,然后调用它的ui应用http://localhost:9999/uaa/logout,调试日志为authserver应用程序提供了以下错误信息,而拒绝退出请求:

Request 'OPTIONS /logout' doesn't match 'POST /logout
Run Code Online (Sandbox Code Playgroud)

应用程序调用注销功能时,需要对示例GitHub应用程序中的代码进行哪些具体更改才能使全局注销成功?uihello.js


初始努力:


到目前为止我所做的更改包括:

将以下@Bean定义添加到AuthserverApplication.java:

@Bean
public TokenStore tokenStore() {return new InMemoryTokenStore();}
Run Code Online (Sandbox Code Playgroud)

demoauthserver应用程序包中添加以下控制器类:

@Configuration
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    TokenStore tokenStore;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore);
    }

    @RequestMapping(value = "/oauth/revoke-token", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public void logout(HttpServletRequest …
Run Code Online (Sandbox Code Playgroud)

spring spring-security spring-boot spring-cloud spring-oauth2

7
推荐指数
1
解决办法
4759
查看次数

将自定义UserDetailsS​​ervice添加到Spring Security OAuth2应用程序

如何添加自定义UserDetailsService下面这个春天的OAuth2样

默认默认user值在应用程序passwordapplication.properties文件中定义authserver.

不过,我想以下自定义添加UserDetailsServicedemo包中的authserver应用程序用于测试目的:

package demo;

import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;

@Service
class Users implements UserDetailsManager {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String password;
        List<GrantedAuthority> auth = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER");
        if (username.equals("Samwise")) {
            auth = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_HOBBIT");
            password = "TheShire";
        }
        else if (username.equals("Frodo")){
            auth = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_HOBBIT");
            password = "MyRing";
        }
        else{throw …
Run Code Online (Sandbox Code Playgroud)

spring spring-security spring-boot spring-security-oauth2 spring-oauth2

7
推荐指数
3
解决办法
1万
查看次数

Spring Boot OAuth2将内部用户与Facebook/Google登录链接起来

我已经使用AngularJS前端实现了一个Spring Boot应用程序.还设置了用户及其权限.现在,我可以使用这些用户登录,并且可以很好地使用Spring安全性.我想将此传统登录流程转换为Facebook/Google OAuth登录流程,我希望用户使用其Facebook/Google帐户登录,并自动将其映射到其内部用户.这将帮助我摆脱维护这些用户的密码.

我发现很多文章都在讨论如何使用Spring Boot设置OAuth,以及如何将Facebook/Google登录与Spring Boot应用程序集成.但我很难找到一篇文章谈论将Facebook/Google用户与内部用户联系起来.

我该怎么办呢?

spring-security spring-social google-oauth spring-boot spring-oauth2

7
推荐指数
1
解决办法
535
查看次数

在Resource Server控制器中访问Spring OAuth 2 JWT有效负载?

我正在阅读本教程,了解如何使用jwt设置spring boot oauth.它包括使用Angular解码JWT令牌,但是我们如何解码它并获取对Resource Server控制器内的自定义声明的访问权限?

例如,使用JJWT可以这样做(基于这篇文章):

    String subject = "HACKER";
    try {
        Jws jwtClaims = 
            Jwts.parser().setSigningKey(key).parseClaimsJws(jwt);

        subject = claims.getBody().getSubject();

        //OK, we can trust this JWT

    } catch (SignatureException e) {

        //don't trust the JWT!
    }
Run Code Online (Sandbox Code Playgroud)

Spring有一个JWTAccessTokenConverter.decode()方法,但缺少javadoc,它受到保护.

java spring-security jwt spring-boot spring-oauth2

7
推荐指数
1
解决办法
7151
查看次数

我如何实现自定义身份验证?

我必须将我的系统与第三方提供商集成.该系统由Spring和Angular制作.

请记住,我需要创建自定义登录表单,而不是重定向到OAuth2等第三方提供商表单.

他创建了以下端点:

获取令牌身份验证

POST http://example.com/webapi/api/web/token

“username=972.344.780-00&password=123456&grant_type=password”
Run Code Online (Sandbox Code Playgroud)

响应发送给我一个我必须在所有下一个请求中使用的令牌.

获取用户信息

Authorization: Bearer V4SQRUucwbtxbt4lP2Ot_LpkpBUUAl5guvxAHXh7oJpyTCGcXVTT-yKbPrPDU9QII43RWt6zKcF5m0HAUSLSlrcyzOuJE7Bjgk48enIoawef5IyGhM_PUkMVmmdMg_1IdIb3Glipx88yZn3AWaneoWPIYI1yqZ9fYaxA-_QGP17Q-H2NZWCn2lfF57aHz8evrRXNt_tpOj_nPwwF5r86crEFoDTewmYhVREMQQjxo80

GET http://example.com/webapi/api/web/userInfo
Run Code Online (Sandbox Code Playgroud)

那就是说,我需要实现自定义身份验证?

在这种情况下我可以使用Spring OAuth2吗?

java spring spring-security angularjs spring-oauth2

7
推荐指数
1
解决办法
1779
查看次数

Spring Security HttpSecurity 配置

我尝试了解 RequestMatcher、AntMatcher 等是如何工作的。我阅读了一些帖子并了解了基础知识。实际上我有这个简单的基本配置:

\n\n
@Override\nprotected void configure(HttpSecurity http) throws Exception {\n    http.requestMatchers() //1\n        .antMatchers("/login", "/oauth/authorize") //2\n        .and() //3\n        .authorizeRequests() //4\n        .anyRequest() //5\n        .authenticated() //6;\n
Run Code Online (Sandbox Code Playgroud)\n\n

我真的不明白第 1,2 和 3 点。根据我的理解,这意味着/login和的请求/oauth/authorize请求被映射并且应该是授权请求。所有其他请求都需要进行身份验证。

\n\n

对于端点来说,/user/me我必须进行身份验证,因为它由第 5 点和第 6 点规定?\n对此端点的调用对我有用。

\n\n

在我的其他配置中,我尝试了一种不同的方法:

\n\n
@Override\nprotected void configure(HttpSecurity http) throws Exception { // @formatter:off\n      http\n       .authorizeRequests() //1\n        .antMatchers("/login", "/oauth/authorize", "/img/**").permitAll() //2\n        .anyRequest() //3\n        .authenticated() //4\n
Run Code Online (Sandbox Code Playgroud)\n\n

从我的角度来看,这应该与第一个配置的逻辑相同。但实际上端点/user/me不再可访问。

\n\n

我非常感谢您的澄清

\n\n
\n\n

更新1:

\n\n

这是我现在的配置:

\n\n
@Override\nprotected void configure(HttpSecurity …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security spring-boot spring-oauth2

7
推荐指数
1
解决办法
6082
查看次数

spring boot oauth ExceptionHandlerExceptionResolver:NestedServletException:嵌套异常是java.lang.StackOverflowError]

我使用 spring boot oauth 2 创建了一个授权。我无法使用数据库中的数据获取访问令牌。

我的授权服务器:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private PropertyConfiguration propertyConfiguration;

    @Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }
    @Override
    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient(propertyConfiguration.getPasswordId())
                .secret(passwordEncoder.encode(propertyConfiguration.getPasswordSecret()))
                .authorizedGrantTypes("password")
                .scopes(SCOPE_WRITE)
                .autoApprove(true);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .tokenStore(tokenStore())
                .authenticationManager(authenticationManager);
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }
Run Code Online (Sandbox Code Playgroud)

我的主课:

@SpringBootApplication
@EntityScan(basePackages = …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate spring-boot spring-oauth2

7
推荐指数
1
解决办法
288
查看次数

Spring Boot Oauth2 资源服务器 UserDetailsS​​ervice

尝试让 UserDetailsS​​ervice 为我设置的 oauth2 资源服务器工作。我能够成功验证 jwt,但我似乎没有做任何事情来让它调用 loadUserByUsername 方法。最初使用 SAML 并且它可以工作,但现在我已经切换到 Oauth2,但我无法让它工作。

     @Service
     public class OauthUsersDetailsServiceImpl implements UserDetailsService{
         @Override
         public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
             //some user loading junk here - this is never called
         }
     }
Run Code Online (Sandbox Code Playgroud)
     @Configuration
        @EnableGlobalMethodSecurity(prePostEnabled = true)
        @EnableWebSecurity
         public class SecurityConfig extends WebSecurityConfigurerAdapter {
            
            @Override
            protected void configure(HttpSecurity http) throws Exception
            {
                //test key for now
                SecretKeySpec key = new SecretKeySpec("private key0000000000000000000000000000000".getBytes(), "HMACSHA256");
                

                http
                    .authorizeRequests()
                    .antMatchers(/*some endpoints im excluding from auth - this all works*/)
                    .permitAll().and() …
Run Code Online (Sandbox Code Playgroud)

spring-security spring-boot spring-security-oauth2 userdetailsservice spring-oauth2

7
推荐指数
1
解决办法
2549
查看次数