标签: spring-security-oauth2

带安全OAuth2的Spring Boot - 如何使用Web登录表单使用资源服务器?

我有一个Spring Boot(1.2.1.RELEASE)应用程序,它在一个应用程序实例中提供OAuth2(2.0.6.RELEASE)授权和资源服务器.它使用自定义UserDetailsService实现MongoTemplate来搜索MongoDB中的用户.使用grant_type=passwordon进行身份验证/oauth/token就像魅力一样,以及Authorization: Bearer {token}在调用特定资源时使用标头进行授权.

现在我想向服务器添加简单的OAuth确认对话框,因此我可以在api-docs中对受保护资源进行身份验证和授权,例如Swagger UI调用.这是我到目前为止所做的:

@Configuration
@SessionAttributes("authorizationRequest")
class OAuth2ServerConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/oauth/confirm_access").setViewName("authorize");
    }

    @Configuration
    @Order(2)
    protected static class LoginConfig extends WebSecurityConfigurerAdapter implements ApplicationEventPublisherAware {

        @Autowired
        UserDetailsService userDetailsService

        @Autowired
        PasswordEncoder passwordEncoder

        ApplicationEventPublisher applicationEventPublisher


        @Bean
        DaoAuthenticationProvider daoAuthenticationProvider() {
            DaoAuthenticationProvider provider = new DaoAuthenticationProvider()
            provider.passwordEncoder = passwordEncoder
            provider.userDetailsService = userDetailsService
            return provider
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception …
Run Code Online (Sandbox Code Playgroud)

spring-security spring-boot spring-security-oauth2

13
推荐指数
2
解决办法
2万
查看次数

Spring OAuth2 - oauth/authorize上的自定义"OAuth Approval"页面

建议自定义页面OAuth审批页面的建议方法是:

默认页面

我必须完全覆盖页面上的内容,需要添加样式,品牌等.实现这一目标的正确方法是什么?我在哪里可以看到默认页面的来源将其用作起点?

我还需要覆盖/ login页面,但我认为覆盖它的方法几乎是一样的.

spring-security spring-security-oauth2

13
推荐指数
2
解决办法
7028
查看次数

Spring OAuth2 - 没有客户端身份验证.尝试添加适当的身份验证筛选器

我们有一个正在使用的应用程序spring-security-oauth2:1.0.我试图将其更改为更新版本spring-security-oauth2:2.0.7.RELEASE.一些类被删除,一些包结构被更改,我设法整理所有这些东西,我能够没有任何问题启动服务器.但我在这里遇到一个奇怪的问题.

随着OAuth2 - 1.0 version,当我们在用户登录使用做了GET要求/oauth/token,例如:

HTTP://本地主机:8080 /回声/的OAuth /令牌grant_type =密码&CLIENT_ID = WS&client_secret =秘密及范围=读,写和用户名=约翰@ abc.com和密码= password123

它以前工作得很好.

当我尝试同样的事情时,首先GET由于TokenEndPoint.java中的逻辑,我无法提出请求

private Set<HttpMethod> allowedRequestMethods = new HashSet<HttpMethod>(Arrays.asList(HttpMethod.POST));

@RequestMapping(value = "/oauth/token", method=RequestMethod.GET)
public ResponseEntity<OAuth2AccessToken> getAccessToken(Principal principal, @RequestParam
Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
    if (!allowedRequestMethods.contains(HttpMethod.GET)) {
        throw new HttpRequestMethodNotSupportedException("GET");
    }
    return postAccessToken(principal, parameters);
}
Run Code Online (Sandbox Code Playgroud)

我试图POST提出与上述URL相同的请求,但我收到InsufficientAuthenticationException了错误消息

没有客户端身份验证.尝试添加适当的身份验证筛选器

这是因为下面的POST请求控制器TokenEndpoint.java.当我调试时,我看到它principal是null.

@RequestMapping(value = "/oauth/token", method=RequestMethod.POST)
    public …
Run Code Online (Sandbox Code Playgroud)

spring-security access-token spring-security-oauth2

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

撤销JWT Oauth2刷新令牌

我试图找到一种方法来撤销Oauth2 JWT刷新令牌与vanilla Spring实现和JwtTokenStore.

首先:有人可以确认没有类似于/ oauth/token的API允许我撤销刷新令牌吗?

我想添加一个自定义API,它将沿着以下行删除刷新令牌:

OAuth2RefreshToken oauth2RefreshToken=tokenStore.readRefreshToken(refreshToken);
tokenStore.removeRefreshToken(oauth2RefreshToken);
Run Code Online (Sandbox Code Playgroud)

现在,看着JwtTokenStore,我注意到它使用了ApprovalStore.所以我继续向我的JwtTokenStore提供了一个InMemoryApprovalStore.我的JwtTokenStore实例化看起来如下:

@Bean
protected JwtAccessTokenConverter jwtTokenEnhancer() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setSigningKey("123456");
    return converter;
}

@Bean
public JwtTokenStore getTokenStore(){
    tokenStore= new JwtTokenStore(jwtTokenEnhancer());
    tokenStore.setApprovalStore(new InMemoryApprovalStore());
    tokenStore.setTokenEnhancer(jwtTokenEnhancer());
    return tokenStore;
};
Run Code Online (Sandbox Code Playgroud)

结果:没有InMemoryApprovalStore,我可以对用户进行身份验证并刷新令牌而不会出现问题.但是,只要我将InMemoryApprovalStore添加到令牌存储,我就会收到以下错误消息:

{"error":"invalid_grant","error_description":"Invalid refresh token: eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NDUwMjQ2MTcsInVzZXJfbmFtZSI6IjYzZjIyYjZlLWU5MGUtNDFjYS1iYzJlLTBmZTgzNmY3MTQ2NyIsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iLCJST0xFX1VTRVIiXSwianRpIjoiMjgwMDgwNWQtMjk1Zi00ZDQzLWI2NTYtMDNlZWYwMWFkMjg0IiwiY2xpZW50X2lkIjoid2ViLWNsaWVudCIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSIsInRydXN0Il19.BPC0HqLYjWGM0IFjvsUGGKQ9dyIXSXwMhraCVFIxD0U"}
Run Code Online (Sandbox Code Playgroud)

因此,我的第二个问题是撤销刷新令牌的正确方法是什么?

编辑:我发现以下线程表明ApprovalStore确实是撤销JWT令牌的方法.我现在只需要找出如何正确使用它们.

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

13
推荐指数
1
解决办法
6095
查看次数

如何在Spring中使用JDBC为ClientDetailsS​​erviceConfigurer添加客户端?

我记忆中的事情如下:

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
               .withClient("clientapp")
               .authorizedGrantTypes("password", "refresh_token")
               .authorities("USER")
               .scopes("read", "write")
               .resourceIds(RESOURCE_ID)
               .secret("123456");
}
Run Code Online (Sandbox Code Playgroud)

我想使用JDBC实现.为此,我创建了以下表(使用MySQL):

-- Tables for OAuth token store

CREATE TABLE oauth_client_details (
  client_id               VARCHAR(255) PRIMARY KEY,
  resource_ids            VARCHAR(255),
  client_secret           VARCHAR(255),
  scope                   VARCHAR(255),
  authorized_grant_types  VARCHAR(255),
  web_server_redirect_uri VARCHAR(255),
  authorities             VARCHAR(255),
  access_token_validity   INTEGER,
  refresh_token_validity  INTEGER,
  additional_information  VARCHAR(4096),
  autoapprove             TINYINT
);

CREATE TABLE oauth_client_token (
  token_id          VARCHAR(255),
  token             BLOB,
  authentication_id VARCHAR(255),
  user_name         VARCHAR(255),
  client_id         VARCHAR(255)
);

CREATE TABLE oauth_access_token (
  token_id          VARCHAR(255),
  token             BLOB,
  authentication_id VARCHAR(255), …
Run Code Online (Sandbox Code Playgroud)

java mysql spring-security-oauth2

13
推荐指数
2
解决办法
2万
查看次数

使用OAuth2和JWT的Spring Security:编码密码看起来不像BCrypt

我正在尝试使用JWT实现spring AuthorizationServer.我能够生成JWT令牌并登录,直到我将BCrypt添加到混音中.现在,当我尝试登录时,我从API获得"Bad credentials".

OAuth2Configuration.java

@Configuration
@EnableAuthorizationServer
public class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {

    private DataSource dataSource;
    private AuthenticationManager authenticationManager;
    private BCryptPasswordEncoder passwordEncoder;

    public OAuth2Configuration(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        this.dataSource = new Jdbc3PoolingDataSource();
        this.passwordEncoder = new BCryptPasswordEncoder();
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.passwordEncoder(passwordEncoder);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("api-client")
                .secret("verysecretivesecret")
                .scopes("READ", "WRITE", "DELETE")
                .authorizedGrantTypes("implicit", "refresh_tokens", "password", "authorization_code");
    }

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

    @Bean …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security spring-security-oauth2 spring-cloud

13
推荐指数
2
解决办法
8264
查看次数

Spring boot 2.0.0.M6 OAuth2 Web应用程序客户端.不再是@ EnableOauth2Sso了; 如何更换?

我在Spring 5和Spring boot 2.0.0.M3中构建了一个Authentication Service和Webapplication,我正试图将它移植到Spring boot 2.0.0.M6现在.

我注意到@EnableOauth2Sso它不再可用了spring-boot-autoconfigure; 我曾使用这个注释来配置我的Web应用程序spring boot 2.0.0.M3.我已经查看了Spring用于配置Oauth2 Client使用的示例,@EnableOAuth2Client但示例中使用的Configuration对象UserInfoTokenServices似乎也不再存在.

如何配置我的客户端Web应用程序OAuth2 in spring boot versions >= 2.0.0.M6

spring spring-boot spring-security-oauth2

13
推荐指数
2
解决办法
2307
查看次数

依赖于已弃用类的 OAuth2FeignRequestInterceptor 的替代方案

免责声明:老实说,我尝试在 google/github 上搜索,扫描了OAuth2 迁移指南,但找不到答案,所以我们开始吧。

来自 spring-cloud-security 项目的org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor获取 OAuth2 令牌并将其设置为对客户端调用者透明的 Feign 的 RequestTemplate。
但是,它依赖于已弃用的OAuth2ClientContext类,该类引用了前面提到的迁移指南,该指南仍然说

对于其他流,需要构造和公开 OAuth2ClientContext 实例。

所以知道几件事会很好:
1.它真的被弃用了,或者只是它的用法应该改变(至少在某些情况下)?
2. 如果是前者 - 正确的选择是什么?
3. 是否有计划OAuth2FeignRequestInterceptor从使用已弃用的类迁移?

spring-security spring-security-oauth2 spring-cloud

13
推荐指数
1
解决办法
1030
查看次数

如何使用RemoteTokenService?

我有一个使用Spring-Security-oauth2构建的独立ResourceServer.这是代码RemoteTokenService.

@Bean
public ResourceServerTokenServices tokenService() {
   RemoteTokenServices tokenServices = new RemoteTokenServices();
   tokenServices.setClientId("sample_test_client_app");
   tokenServices.setClientSecret("secret");
   tokenServices.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
   return tokenServices;
}
Run Code Online (Sandbox Code Playgroud)

当我使用AccessToken访问资源服务器时,我得到以下内容:

FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /oauth/check_token; Attributes: [denyAll()]
FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@c3f3b25: Principal: org.springframework.security.core.userdetails.User@3c0cd8e: Username: sample_test_client_app; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities
AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@6172e10, returned: -1
ExceptionTranslationFilter - Access is denied (user is not anonymous); delegating …
Run Code Online (Sandbox Code Playgroud)

spring spring-security access-token oauth-2.0 spring-security-oauth2

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

使用Spring Security从JWT令牌中提取当前登录的用户信息

我使用Spring Security Oauth2实现了JWT和LDAP身份验证.它似乎工作正常,我可以使用我的LDAP凭据登录.

现在,有一个要求我需要使用当前登录的用户信息来保存数据库中的详细信息 - 特别是当该用户添加/更新新记录时.我尝试使用Spring安全方式来实现

SecurityContextHolder.getContext().getAuthentication().getDetails() 
Run Code Online (Sandbox Code Playgroud)

但它不会返回我在JWT中获得的所有信息.它只返回远程IP,JWT令牌值和经过身份验证的true.它甚至没有返回name().

我是JWT的新手,所以不确定我是否需要通过阅读该令牌来提取它,甚至我们如何实现它.

任何指针将不胜感激.

谢谢.

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

12
推荐指数
1
解决办法
7932
查看次数