标签: spring-security-oauth2

将用户角色映射到oauth2范围/权限

我们有一个权利数据库,其中包含应用程序ID,角色和用户映射到每个应用程序的角色.遵循线程建议如何基于resourceId将用户角色映射到oauth2范围/权限?

忽略我上面提到的权利数据库,我是否根据下面代码中的user和resourceId将角色"USER","READER","WRITER"映射到oauth2范围/权限?

用户认证/授权配置

@Configuration
@Order(-10)
protected static class LoginConfig extends WebSecurityConfigurerAdapter {

    ....

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // auth.parentAuthenticationManager(authenticationManager);
        // @formatter:off
        auth.inMemoryAuthentication()
            .withUser("admin").password("admin")
                .roles("ADMIN", "USER", "READER", "WRITER")
            .and()
            .withUser("user").password("password")
                .roles("USER")
            .and()
            .withUser("audit").password("audit")
                .roles("USER", "ADMIN", "READER");
        // @formatter:on
    }
}
Run Code Online (Sandbox Code Playgroud)

OAuth2配置

@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // @formatter:off
        clients.inMemory()
            .withClient("acme").secret("acmesecret")
                .authorizedGrantTypes("authorization_code", "refresh_token", "password")
                .scopes("openid")
            .and() …
Run Code Online (Sandbox Code Playgroud)

spring-security spring-security-oauth2

15
推荐指数
1
解决办法
5763
查看次数

Spring Boot 1.3.3 @EnableResourceServer和@ EnableOAuth2Sso同时进行

我希望我的服务器是ResourceServer,它可以接受承载访问令牌

但是,如果此类令牌不存在,我想使用OAuth2Server对我的用户进行身份验证.

我尝试这样做:

@Configuration
@EnableOAuth2Sso
@EnableResourceServer
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,在这种情况下,只有@EnableResourceServer注释有效.它回来了

Full authentication is required to access this resource
Run Code Online (Sandbox Code Playgroud)

并且不要将我重定向到登录页面

我提到@Order重要的是,如果我添加@Order(0)注释,我将重定向到登录页面,但是,我无法使用Http标头中的access_token访问我的资源:

Authorization : Bearer 142042b2-342f-4f19-8f53-bea0bae061fc
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现目标?我希望它同时使用Access令牌和SSO.

谢谢〜

spring spring-boot spring-security-oauth2

15
推荐指数
1
解决办法
2980
查看次数

邮递员中不支持的媒体类型

我正在用oauth2和jwt实现spring security.以下是我的登录功能

function doLogin(loginData) {

    $.ajax({
        url :  back+"/auth/secret",
        type : "POST",
        data : JSON.stringify(loginData),
        contentType : "application/json; charset=utf-8",
        dataType : "json",
        async : false,
        success : function(data, textStatus, jqXHR) {

            setJwtToken(data.token);


        },
        error : function(jqXHR, textStatus, errorThrown) {
            alert("an unexpected error occured: " + errorThrown);
            window.location.href= back+'/login_page.html';
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

而且我有控制器

 @RequestMapping(value = "auth/secret", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {
        System.out.println();
        logger.info("authentication request : " + authenticationRequest.getUsername() + " " + authenticationRequest.getPassword()); …
Run Code Online (Sandbox Code Playgroud)

spring spring-security jwt spring-security-oauth2

15
推荐指数
5
解决办法
6万
查看次数

Spring Boot + Spring Security + Spring OAuth2 + Google登录

我已经设置了一个小项目,使用Spring Boot(1.5.2),Spring Security和Spring Security OAuth2实施OAuth2使用Google+ API登录.

您可以在以下网址找到来源:https://github.com/ccoloradoc/OAuth2Sample

我可以通过谷歌进行身份验证并提取用户信息.但是,在我注销后,由于我尝试将" https://accounts.google.com/o/oauth2/auth "与我的RestTemplate 连接以调用google api ,因此我收到"400 Bad Request"后无法再次登录.

有关进一步参考,请参阅Filter attemptAuthentication方法.

这是我的安全配置类

@Configuration
@EnableGlobalAuthentication
@EnableOAuth2Client
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
@PropertySource(value = {"classpath:oauth.properties"})
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Autowired
    private UserDetailsService userDetailsService;

    @Resource
    @Qualifier("accessTokenRequest")
    private AccessTokenRequest accessTokenRequest;

    @Autowired
    private OAuth2ClientContextFilter oAuth2ClientContextFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.
                authorizeRequests()
                .antMatchers(HttpMethod.GET, "/login","/public/**", "/resources/**","/resources/public/**").permitAll()
                .antMatchers("/google_oauth2_login").anonymous()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/")
                .and()
                .csrf().disable()
                .logout()
                .logoutSuccessUrl("/") …
Run Code Online (Sandbox Code Playgroud)

spring google-api spring-security spring-security-oauth2

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

Spring Security oauth2 客户端 - Twitter 问题

我想将 Twitter oAuth2 添加到我的应用程序中。早些时候,我成功添加了 Facebook 和 google - 我不必添加提供商。当我尝试将 twitter 数据添加到application.properties文件并运行服务器时,出现错误:

Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'securityConfig': Unsatisfied dependency expressed through method 'setContentNegotationStrategy' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration': Unsatisfied dependency expressed through method 'setConfigurers' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration$OAuth2ClientWebMvcSecurityConfiguration': Unsatisfied dependency expressed through method 'setClientRegistrationRepository' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientRegistrationRepositoryConfiguration': …
Run Code Online (Sandbox Code Playgroud)

java twitter-oauth spring-boot spring-security-oauth2

15
推荐指数
1
解决办法
2065
查看次数

如何处理spring-security-oauth2的版本升级?

spring-security-oauth2将Authentication对象作为序列化java对象(ByteArrayOutputStream.writeObject(authentication))保存在数据库中作为访问令牌条目的一部分.

你如何处理spring-security(可能会改变SpringSecurityCoreVersion.SERIAL_VERSION_UID)和spring-security-oauth(可能改变了serialVersionUID OAuth2Authentication)的版本升级?如果serialVersionUID发生更改,则无法再对反序列化持久化的Authentication对象.

我们得出的结论是,在升级框架版本时,删除包含序列化身份验证对象的访问令牌将是最干净,最简单的解决方案.任何想法如何更优雅地处理这个?

java serialization spring spring-security spring-security-oauth2

14
推荐指数
1
解决办法
755
查看次数

如何在Spring中注销oauth2客户端?

我有最简单的oauth2客户端:

@EnableAutoConfiguration
@Configuration
@EnableOAuth2Sso
@RestController
public class ClientApplication {

    @RequestMapping("/")
    public String home(Principal user, HttpServletRequest request, HttpServletResponse response) throws ServletException {       
        return "Hello " + user.getName();
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(ClientApplication.class)
                .properties("spring.config.name=application").run(args);
    }

}
Run Code Online (Sandbox Code Playgroud)

我还有以下内容application.yml:

server:
  port: 9999
  servlet:
    context-path: /client
security:
  oauth2:
    client:
      client-id: acme
      client-secret: acmesecret
      access-token-uri: http://localhost:8080/oauth/token
      user-authorization-uri: http://localhost:8080/oauth/authorize
    resource:
      user-info-uri: http://localhost:8080/me

logging:
  level:
    org.springframework.security: DEBUG
    org.springframework.web: DEBUG
Run Code Online (Sandbox Code Playgroud)

这是完整的代码.我没有任何其他源代码.它工作正常.

但现在我想添加一个注销功能.我添加了一个端点,但它不起作用.我试着做以下事情:

@RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        Authentication …
Run Code Online (Sandbox Code Playgroud)

java spring-security oauth-2.0 spring-security-oauth2 spring-oauth2

14
推荐指数
3
解决办法
4209
查看次数

Spring Boot 在 ServerOAuth2AuthorizedClientExchangeFilterFunction 中向 WebClient 请求添加附加属性

我正在尝试实现 client_credentials 授予以在我的 Spring Boot 资源服务器中获取令牌。我使用Auth0作为授权服务器。他们似乎需要在请求正文中添加一个名为“audience”的额外参数。

我尝试通过邮递员提出请求并且它有效。我现在正尝试在 Spring 内重现它。这是工作邮递员的请求

curl -X POST \
  https://XXX.auth0.com/oauth/token \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'grant_type=client_credentials&audience=https%3A%2F%2Fxxxxx.auth0.com%2Fapi%2Fv2%2F&client_id=SOME_CLIENT_ID&client_secret=SOME_CLIENT_SECRET'
Run Code Online (Sandbox Code Playgroud)

我面临的问题是我无法将缺少的受众参数添加到令牌请求中。

我在 application.yml 中定义了一个配置

client:
    provider:
      auth0:
        issuer-uri: https://XXXX.auth0.com//
    registration:
      auth0-client:
        provider: auth0
        client-id: Client
        client-secret: Secret
        authorization_grant_type: client_credentials
      auth0:
        client-id: Client
        client-secret: Secret
Run Code Online (Sandbox Code Playgroud)

我的网络客户端过滤器是这样配置的。

@Bean
WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations,
                    ServerOAuth2AuthorizedClientRepository authorizedClients) {
    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2 = new ServerOAuth2AuthorizedClientExchangeFilterFunction(
            clientRegistrations, authorizedClients);
    oauth2.setDefaultClientRegistrationId("auth0");
    return WebClient.builder()
            .filter(oauth2)
            .build();
}
Run Code Online (Sandbox Code Playgroud)

我正在注入实例并尝试发出请求以通过电子邮件获取用户

 return this.webClient.get()
            .uri(this.usersUrl + "/api/v2/users-by-email?email={email}", email)
            .attributes(auth0ClientCredentials())
            .retrieve()
            .bodyToMono(User.class);
Run Code Online (Sandbox Code Playgroud)

按照我的理解,过滤器拦截此 userByEmail …

spring-boot spring-security-oauth2 auth0

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

AuthorizationServerConfigurerAdapter 已弃用

我想Oauth2在 spring rest API 中使用身份验证进行登录。但是我收到了一些警告,例如Spring Security 5AuthorizationServerConfigurerAdapter is deprecatedOAuth 2.0 迁移指南

课程文档

我在那里检查过,但没有找到很多迁移指南。任何人都可以分享完整的例子。

提前致谢...

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

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

如何在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万
查看次数