GVKun编程网logo

在Spring Boot中配置0足OAuth 1.0(spring boot oauth2.0)

21

如果您对在SpringBoot中配置0足OAuth1.0和springbootoauth2.0感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解在SpringBoot中配置0足OAuth1.0的各

如果您对在Spring Boot中配置0足OAuth 1.0spring boot oauth2.0感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解在Spring Boot中配置0足OAuth 1.0的各种细节,并对spring boot oauth2.0进行深入的分析,此外还有关于java – 在Spring Boot中配置0-legged OAuth 1.0、java – 在Spring Boot中配置Amazon SQS队列名称、Nginx 反向代理Springboot oAuth https配置方案、Spring Boot + OAuth的实用技巧。

本文目录一览:

在Spring Boot中配置0足OAuth 1.0(spring boot oauth2.0)

在Spring Boot中配置0足OAuth 1.0(spring boot oauth2.0)

我想用0腿(因此没有请求或访问令牌)OAuth 1.0设置Spring
Boot应用程序。我一直在挖掘一段时间以尝试查找示例,而我主要停留在如何使用新样式(无xml)配置方面。

现在,我只想得到一个简单的用例,其中只有1个路径(/ oauth)受OAuth保护(其他所有内容都是敞开的),并且它使用自定义的
ConsumerDetailsS​​ervice (有关该代码的简单版本,请参见下文)。

这是我的 WebSecurityConfigurerAdapter
(位于Application.java旁边的SecurityConfiguration.java,我认为这是在Spring
Boot应用程序中配置此类操作的正确方法)。我很确定我缺少提供程序配置(如http://projects.spring.io/spring-
security-oauth/docs/oauth1.html中所述),但是我的反复试验没有产生结果。

@Configuration@EnableWebMvcSecurity@EnableGlobalMethodSecurity(prePostEnabled = true)public class SecurityConfiguration extends WebSecurityConfigurerAdapter {    @Override    protected void configure(HttpSecurity http) throws Exception {        // 0-Legged OAuth on the /oauth and /lti paths only        http.requestMatchers().antMatchers("/oauth"); // .and().... what?        // ??? something must be missing here - provider?    }}

我的maven pom.xml中也有这个:

<!-- security and oauth --><dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-security</artifactId></dependency><!-- OAuth --><dependency>  <groupId>org.springframework.security.oauth</groupId>  <artifactId>spring-security-oauth</artifactId>  <version>2.0.2.RELEASE</version></dependency>

我的自定义ConsumerDetailsS​​ervice

@Componentpublic class LTIConsumerDetailsService implements ConsumerDetailsService {    @Override    public ConsumerDetails loadConsumerByConsumerKey(String consumerKey) throws OAuthException {        BaseConsumerDetails cd;        // TODO really lookup the key and related consumer details, for sample here we just hardcoded        if ("key".equals(consumerKey)) {            cd = new BaseConsumerDetails();            cd.setConsumerKey(consumerKey);            cd.setSignatureSecret(new SharedConsumerSecretImpl("secret"));            cd.setConsumerName("Sample consumerName");            cd.setRequiredToObtainAuthenticatedToken(false); // no token required (0-legged)            cd.setResourceDescription("Sample consumer details - AZ");            cd.setResourceName("Sample resourceName");        } else {            throw new OAuthException("For this example, key must be ''key''");        }        return cd;    }}

任何有关如何使此工作正常运行的建议或指向Spring Boot OAuth 1.0代码的指针将不胜感激。请注意,我已经尝试查看单独的spring
boot安全性和OAuth指南,但无法成功合并它们。

答案1

小编典典

这是我如何通过Java Config在spring-boot 1.1.4中获得0腿OAuth 1.0的工作方式。

注意:就我而言,我只希望OAuth保护单个路径(/ oauth /
**),因此,如果希望保护所有内容,则可以简化其中的某些部分。您可以在这里查看我的完整代码:https://github.com/azeckoski/lti_starter

一旦拥有了下面显示的最少部分,您就应该能够运行spring-boot应用程序,并使用ConsumerKey:key和Secret:secret在/
oauth处触发OAuth 1.0兼容请求,并成功加载路径。

应用程序

重要说明
:(1)不要只是将ZeroLeggedOAuthProviderProcessingFilter声明为Bean,否则将影响所有路径(它将自动被spring拾取)。(2)如果要访问,则必须存在NoAuthConfigurationAdapter受保护路径之外的安全数据(在本例中为/
oauth)

@ComponentScan@Configuration@EnableAutoConfiguration@EnableWebMvcSecurity // enable spring security and web mvc hooks@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)public class Application extends WebMvcConfigurerAdapter {    final static Logger log = LoggerFactory.getLogger(Application.class);    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }    // Spring Security    @Autowired    @Order(Ordered.HIGHEST_PRECEDENCE + 10)    @SuppressWarnings("SpringJavaAutowiringInspection")    public void configureSimpleAuthUsers(AuthenticationManagerBuilder auth) throws Exception {        auth.inMemoryAuthentication()                .withUser("admin").password("admin").roles("ADMIN", "USER")                .and().withUser("user").password("user").roles("USER");    }    @Configuration    @Order(1) // HIGHEST    public static class OAuthSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {        private ZeroLeggedOAuthProviderProcessingFilter zeroLeggedOAuthProviderProcessingFilter;        @Autowired        OAuthConsumerDetailsService oauthConsumerDetailsService;        @Autowired        OAuthAuthenticationHandler oauthAuthenticationHandler;        @Autowired        OAuthProcessingFilterEntryPoint oauthProcessingFilterEntryPoint;        @Autowired        OAuthProviderTokenServices oauthProviderTokenServices;        @PostConstruct        public void init() {            zeroLeggedOAuthProviderProcessingFilter = new ZeroLeggedOAuthProviderProcessingFilter(oauthConsumerDetailsService, new InMemoryNonceServices(), oauthProcessingFilterEntryPoint, oauthAuthenticationHandler, oauthProviderTokenServices);        }        @Override        protected void configure(HttpSecurity http) throws Exception {            http.antMatcher("/oauth/**")                    .addFilterBefore(zeroLeggedOAuthProviderProcessingFilter, UsernamePasswordAuthenticationFilter.class)                    .authorizeRequests().anyRequest().hasRole("OAUTH");        }    }    @Order(45) // LOW    @Configuration    public static class BasicAuthConfigurationAdapter extends WebSecurityConfigurerAdapter {        @Override        protected void configure(HttpSecurity http) throws Exception {            http.antMatcher("/basic/**").authorizeRequests().anyRequest().authenticated()                    .and().httpBasic();        }    }    @Order(67) // LOWEST    @Configuration    public static class NoAuthConfigurationAdapter extends WebSecurityConfigurerAdapter {        @Override        protected void configure(HttpSecurity http) throws Exception {            http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();        }    }    // OAuth beans    public static class OAuthProcessingFilterEntryPointImpl extends OAuthProcessingFilterEntryPoint {        @Override        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {            log.info("OAuth FILTER Failure (commence), req=" + request + ", ex=" + authException);            // Called when there is an OAuth Auth failure, authException may be InsufficientAuthenticationException            super.commence(request, response, authException);        }    }    @Bean(name = "oauthAuthenticationEntryPoint")    public OAuthProcessingFilterEntryPoint oauthAuthenticationEntryPoint() {        return new OAuthProcessingFilterEntryPointImpl();    }    @Bean(name = "oauthProviderTokenServices")    public OAuthProviderTokenServices oauthProviderTokenServices() {        // NOTE: we don''t use the OAuthProviderTokenServices for 0-legged but it cannot be null        return new InMemoryProviderTokenServices();    }    public static class ZeroLeggedOAuthProviderProcessingFilter extends ProtectedResourceProcessingFilter {        ZeroLeggedOAuthProviderProcessingFilter(OAuthConsumerDetailsService oAuthConsumerDetailsService, OAuthNonceServices oAuthNonceServices, OAuthProcessingFilterEntryPoint oAuthProcessingFilterEntryPoint, OAuthAuthenticationHandler oAuthAuthenticationHandler, OAuthProviderTokenServices oAuthProviderTokenServices) {            super();            log.info("CONSTRUCT Zero Legged OAuth provider");            setAuthenticationEntryPoint(oAuthProcessingFilterEntryPoint);            setAuthHandler(oAuthAuthenticationHandler);            setConsumerDetailsService(oAuthConsumerDetailsService);            setNonceServices(oAuthNonceServices);            setTokenServices(oAuthProviderTokenServices);            //setIgnoreMissingCredentials(false); // die if OAuth params are not included        }    }}

OAuthConsumerDetailsS​​ervice.java

@Componentpublic class OAuthConsumerDetailsService implements ConsumerDetailsService {    final static Logger log = LoggerFactory.getLogger(OAuthConsumerDetailsService.class);    @Override    public ConsumerDetails loadConsumerByConsumerKey(String consumerKey) throws OAuthException {        BaseConsumerDetails cd;        // NOTE: really lookup the key and secret, for the sample here we just hardcoded        if ("key".equals(consumerKey)) {            // allow this oauth request            cd = new BaseConsumerDetails();            cd.setConsumerKey(consumerKey);            cd.setSignatureSecret(new SharedConsumerSecretImpl("secret"));            cd.setConsumerName("Sample");            cd.setRequiredToObtainAuthenticatedToken(false); // no token required (0-legged)            cd.getAuthorities().add(new SimpleGrantedAuthority("ROLE_OAUTH")); // add the ROLE_OAUTH (can add others as well)            log.info("OAuth check SUCCESS, consumer key: " + consumerKey);        } else {            // deny - failed to match            throw new OAuthException("For this example, key must be ''key''");        }        return cd;    }}

MyOAuthAuthenticationHandler.java

最后一部分对于根据来自OAuth请求的数据定义实际用户(和Principal)很重要。这将取决于您在本地处理事物的方式而有所不同,但这是如何执行此操作的示例。

@Componentpublic class MyOAuthAuthenticationHandler implements OAuthAuthenticationHandler {        final static Logger log = LoggerFactory.getLogger(MyOAuthAuthenticationHandler.class);    static SimpleGrantedAuthority userGA = new SimpleGrantedAuthority("ROLE_USER");    static SimpleGrantedAuthority adminGA = new SimpleGrantedAuthority("ROLE_ADMIN");    @Override    public Authentication createAuthentication(HttpServletRequest request, ConsumerAuthentication authentication, OAuthAccessProviderToken authToken) {        Collection<GrantedAuthority> authorities = new HashSet<>(authentication.getAuthorities());        // attempt to create a user Authority        String username = request.getParameter("username");        if (StringUtils.isBlank(username)) {            username = authentication.getName();        }        // NOTE: you should replace this block with your real rules for determining OAUTH ADMIN roles        if (username.equals("admin")) {            authorities.add(userGA);            authorities.add(adminGA);        } else {            authorities.add(userGA);        }        Principal principal = new NamedOAuthPrincipal(username, authorities,                authentication.getConsumerCredentials().getConsumerKey(),                authentication.getConsumerCredentials().getSignature(),                authentication.getConsumerCredentials().getSignatureMethod(),                authentication.getConsumerCredentials().getSignatureBaseString(),                authentication.getConsumerCredentials().getToken()        );        Authentication auth = new UsernamePasswordAuthenticationToken(principal, null, authorities);        return auth;    }    public static class NamedOAuthPrincipal extends ConsumerCredentials implements Principal {        public String name;        public Collection<GrantedAuthority> authorities;        public NamedOAuthPrincipal(String name, Collection<GrantedAuthority> authorities, String consumerKey, String signature, String signatureMethod, String signatureBaseString, String token) {            super(consumerKey, signature, signatureMethod, signatureBaseString, token);            this.name = name;            this.authorities = authorities;        }        @Override        public String getName() {            return name;        }        public Collection<? extends GrantedAuthority> getAuthorities() {            return authorities;        }    }}

OAuthController.java

@Controller@RequestMapping("/oauth")public class OAuthController extends BaseController {    @RequestMapping({"", "/"})    public String home(HttpServletRequest req, Principal principal, Model model) {        return "home"; // name of the template    }}

pom.xml(maven-仅关键部分)

<dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-web</artifactId></dependency><!-- security and oauth --><dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-security</artifactId></dependency><!-- OAuth --><dependency>  <groupId>org.springframework.security.oauth</groupId>  <artifactId>spring-security-oauth</artifactId>  <version>2.0.2.RELEASE</version></dependency>

java – 在Spring Boot中配置0-legged OAuth 1.0

java – 在Spring Boot中配置0-legged OAuth 1.0

我想设置一个带有0-legged(因此没有请求或访问令牌)OAuth 1.0的spring boot应用程序.我一直在寻找一个例子,我一直在努力寻找如何使用新风格(没有xml)配置东西.

现在我只想得到一个简单的用例,其中只有1个路径(/ oauth)受OAuth保护(其他一切都只是大开),并且它使用自定义ConsumerDetailsS​​ervice(请参阅下面的代码的简单版本).

这是我的WebSecurityConfigurerAdapter(我的Application.java旁边的SecurityConfiguration.java,我认为这是在spring启动应用程序中配置这种东西的正确方法).我很确定我错过了提供程序配置(如:http://projects.spring.io/spring-security-oauth/docs/oauth1.html中所述),但我的试错法并没有产生结果.

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 0-Legged OAuth on the /oauth and /lti paths only
        http.requestMatchers().antMatchers("/oauth"); // .and().... what?
        // ??? something must be missing here - provider?
    }

}

我在maven pom.xml中也有这个:

总结

以上是小编为你收集整理的java – 在Spring Boot中配置0-legged OAuth 1.0全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

java – 在Spring Boot中配置Amazon SQS队列名称

java – 在Spring Boot中配置Amazon SQS队列名称

我正在使用AmazonSQS& Spring Boot(spring-cloud-aws-messaging).我已经配置了一个消息监听器来使用注释@SqsListener接收来自队列的消息.

@SqsListener(value = "indexerQueue",deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS)
public void queueListener(String rawMessage) {
   ...
}

这是一个非常简单的方法,但我没有找到从配置文件加载队列名称的方法,因为我有不同的环境.关于这方面的任何想法?

解决方法

您使用的是什么版本的spring-cloud-aws-messaging?版本1.1应该允许您使用占位符作为队列名称,例如

@SqsListener(value = "${sqs.queue.indexer}",deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS)
public void queueListener(String rawMessage) {
   ...
}

然后,在application-env.properties文件中,您可以添加不同的值.例如,在application-dev.properties中:

sqs.queue.indexer=devIndexerQueue

在application-production.properties中

sqs.queue.indexer=indexerQueue

Nginx 反向代理Springboot oAuth https配置方案

Nginx 反向代理Springboot oAuth https配置方案

Nginx 配置方案

server {
    listen       80;
    server_name  www.yourname.com;
    rewrite ^(.*)$ https://${server_name}$1 permanent;
}


server {
    listen 443;
    server_name www.yourname.com;
    ssl on;
    root html;
    index index.html index.htm;
    ssl_certificate  /data/cert/yourname.pem;
    ssl_certificate_key  /data/cert/yourname.key;
    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        #proxy_set_header X-Forwarded-Host $host:$server_port;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://127.0.0.1:8080/;
    }

}

springboot YML配置

server:
  port: 8080
  use-forward-headers: true
  tomcat:
    remote_ip_header: x-forwarded-for
    protocol_header: x-forwarded-proto
    port-header: X-Forwarded-Port

Spring Boot + OAuth

Spring Boot + OAuth

OAuthSecurityConfig.java

@Configuration
public class OAuthSecurityConfig extends AuthorizationServerConfigurerAdapter {

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client")
                .secret("secret")
                .redirectUris("http://www.baidu.com")
                .authorizedGrantTypes("authorization_code")
                .scopes("app");
    }
}

DemoApplication.java

@SpringBootApplication
@EnableAuthorizationServer
public class DemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}

build.gradle

dependencies {
	compile(''org.springframework.boot:spring-boot-starter'')

	compile(''com.auth0:java-jwt:2.2.0'')
	compile(''org.springframework.cloud:spring-cloud-starter-security'')
	compile(''org.springframework.cloud:spring-cloud-starter-oauth2'')
	compile(''org.springframework.boot:spring-boot-starter-web'')
	compile(''org.springframework.boot:spring-boot-starter-jersey'')

	testCompile(''org.springframework.boot:spring-boot-starter-test'')
}

之后启动项目访问:localhost:8080/oauth/authorize?client_id=client&response_type=code&redirect_uri=http://www.baidu.com
验证身份,用户名:user,密码:启动的日志中找到Using default security password,之后点授权
获得code码,在url中:https://www.baidu.com/?code=K52t0C

关于在Spring Boot中配置0足OAuth 1.0spring boot oauth2.0的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于java – 在Spring Boot中配置0-legged OAuth 1.0、java – 在Spring Boot中配置Amazon SQS队列名称、Nginx 反向代理Springboot oAuth https配置方案、Spring Boot + OAuth的相关知识,请在本站寻找。

本文标签: