在本文中,我们将详细介绍如何限制到特定域以使用Spring-Boot和OAuth2登录的各个方面,并为您提供关于限制指定ip访问的相关解答,同时,我们也将为您带来关于OAuth2-03-springb
在本文中,我们将详细介绍如何限制到特定域以使用Spring-Boot和OAuth2登录的各个方面,并为您提供关于限制指定ip访问的相关解答,同时,我们也将为您带来关于OAuth2-03-springboot 整合、Spring Boot + Oauth2客户端凭据、Spring Boot 2.0.0 + OAuth2、Spring Boot 2.5.3 OAuth2 - Auth-Server 和 Webservice 分开,登录错误的有用知识。
本文目录一览:- 如何限制到特定域以使用Spring-Boot和OAuth2登录(限制指定ip访问)
- OAuth2-03-springboot 整合
- Spring Boot + Oauth2客户端凭据
- Spring Boot 2.0.0 + OAuth2
- Spring Boot 2.5.3 OAuth2 - Auth-Server 和 Webservice 分开,登录错误
如何限制到特定域以使用Spring-Boot和OAuth2登录(限制指定ip访问)
我已经使用Spring Boot和Google成功完成了OAuth2登录,但是我想将登录限制为特定的域(我们正在使用Google Apps for
Work)。
我认为我应该通过扩展类OAuth2ClientAuthenticationProcessingFilter来处理所指定,但是我不确定该怎么做。
基本上,我想使用Google OAuth 2.0作为身份提供者,但必须只接受公司用户(@ company.com)。
答案1
小编典典根据Stéphane的建议,我进入了本教程,并最终实现了该方法,该方法适用于我的Google+个人资料:
@Configuration@EnableOAuth2Ssopublic class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String GOOGLE_PLUS_DOMAIN_ATTRIBUTE = "domain"; private static final String CSRF_COOKIE_NAME = "XSRF-TOKEN"; private static final String CSRF_HEADER_NAME = "X-XSRF-TOKEN"; @Bean public AuthoritiesExtractor authoritiesExtractor( @Value("#{''${security.allowed-domains}''.split('','')}") final List<String> allowedDomains) { return new AuthoritiesExtractor() { @Override public List<GrantedAuthority> extractAuthorities(final Map<String, Object> map) { if (map != null && map.containsKey(GOOGLE_PLUS_DOMAIN_ATTRIBUTE)) { final String domain = (String) map.get(GOOGLE_PLUS_DOMAIN_ATTRIBUTE); if (!allowedDomains.contains(domain)) { throw new BadCredentialsException("Not an allowed domain"); } return AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"); } return null; } }; } @Override protected void configure(final HttpSecurity http) throws Exception { // @formatter:off http.antMatcher("/**") .authorizeRequests() .antMatchers("/logout", "/api/mappings/**", "/public/**").permitAll() .anyRequest().hasAuthority("ROLE_USER") .and().logout().logoutUrl("/api/logout").logoutSuccessUrl("/logout") .and().csrf().csrfTokenRepository(csrfTokenRepository()).ignoringAntMatchers("/api/mappings/**") .and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class); // @formatter:on } private Filter csrfHeaderFilter() { return new OncePerRequestFilter() { @Override protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { final CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); if (csrf != null) { Cookie cookie = WebUtils.getCookie(request, CSRF_COOKIE_NAME); final String token = csrf.getToken(); if (cookie == null || token != null && !token.equals(cookie.getValue())) { cookie = new Cookie(CSRF_COOKIE_NAME, token); cookie.setPath("/"); response.addCookie(cookie); } } filterChain.doFilter(request, response); } }; } private CsrfTokenRepository csrfTokenRepository() { final HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); repository.setHeaderName(CSRF_HEADER_NAME); return repository; }}
我的application.yml文件包含有关oauth的以下条目:
security: oauth2: client: access-token-uri: https://www.googleapis.com/oauth2/v3/token user-authorization-uri: https://accounts.google.com/o/oauth2/auth client-authentication-scheme: form scope: profile,email resource: user-info-uri: https://www.googleapis.com/plus/v1/people/me prefer-token-info: false
使用Google+个人资料时,地图中提供的资源服务器响应包含域条目。我只是将此值与配置的允许域进行了比较。
希望这可以帮助。
更新:2019年3月7日,谷歌将弃用Google+
API。如果您像我一样,将会收到Google的电子邮件,建议您更新软件。在我们的情况下,网址https://www.googleapis.com/plus/v1/people/me将会被弃用。因此,我在这里发布了更新的配置(使用Spring
Boot 1.3.5构建)。
security: oauth2: client: clientId: *your client id from Google* clientSecret: *your client secret from Google* accessTokenUri: https://www.googleapis.com/oauth2/v4/token userAuthorizationUri: https://accounts.google.com/o/oauth2/v2/auth clientAuthenticationScheme: form scope: - email - profile resource: userInfoUri: https://www.googleapis.com/oauth2/v3/userinfo preferTokenInfo: false # Comma-separated list of domains allowed-domains: *your allowed domains*
请注意,由于属性域已更改其名称,因此必须在WebSecurityConfigurerAdapter中进行较小的更改。因此,您需要替换以下行:
私有静态最终字符串GOOGLE_PLUS_DOMAIN_ATTRIBUTE =“域”;
与
私有静态最终字符串HOSTED_DOMAIN_ATTRIBUTE =“ hd”;
OAuth2-03-springboot 整合
拓展阅读
OAuth 2.0-01-Overview
OAuth2-02-java 整合
OAuth2-03-springboot 整合
序言
安全性是暴露由许多微服务组成的公共访问API时要考虑的最重要的一个方面。
Spring有一些有趣的功能和框架,使我们的微服务安全配置更容易。
在本文中,我将向您展示如何使用Spring Cloud和Oauth2在API网关后面提供令牌访问安全性。
理论知识
OAuth2标准目前被所有主要网站使用并且允许通过共享API访问其资源。它是一种开放式授权标准,允许用户将存储在一个页面中的私有资源共享到另一个页面,而无需进入其凭据服务。这些是与oauth2相关的基本术语。
Resource Owner – 处理对资源的访问
Resource Server – 存储可以使用特殊令牌共享的所有者资源的服务器
Authorization Server – 管理密钥,令牌和其他临时资源访问代码的分配。它还必须确保授予相关人员访问权限
Access Token – 允许访问资源的密钥
Authorization Grant – 授予访问权限。有多种方法可以确认访问权限:授权代码,隐式,资源所有者密码凭据和客户端凭据
您可以在此处以及在digitalocean文章中阅读有关此标准的更多信息。该协议的流程主要有三个步骤。
首先,我们将授权请求发送给资源所有者。在资源所有者响应后,我们向授权服务器发送授权请求并接收访问令牌。
最后,我们将此访问令牌发送到资源服务器,如果它有效,则API将资源提供给应用程序。
方案
下图显示了我们案例的架构。我们用API网关(Zuul)代理我们对授权服务器的请求和两个帐户微服务实例。
授权服务器是某种提供outh2安全机制的基础结构服务。
我们还有发现服务(Eureka),我们所有的微服务都已注册。
springboot 整合例子
以下是一个简单的Java Spring整合OAuth 2.0的入门例子。这个例子使用Spring Boot构建,并使用Spring Security OAuth2来实现OAuth2.0认证。
在这个例子中,我们将使用GitHub作为OAuth2.0的提供者。
首先,确保你有一个Spring Boot项目的基本结构。
然后,按照以下步骤进行:
- 添加Spring Security OAuth2依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
- 创建一个OAuth2的配置类:
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableOAuth2Sso
public class OAuth2Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/login**").permitAll()
.anyRequest().authenticated();
}
}
- 添加application.yml配置:
spring:
security:
oauth2:
client:
registration:
github:
client-id: YOUR_CLIENT_ID
client-secret: YOUR_CLIENT_SECRET
scope: read:user
provider:
github:
user-name-attribute: login
将YOUR_CLIENT_ID
和YOUR_CLIENT_SECRET
替换为你在GitHub注册应用时获得的客户端ID和客户端密钥。
- 创建一个简单的控制器:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/")
public String hello() {
return "Hello, OAuth2!";
}
}
现在,当你启动应用程序时,它将自动重定向到GitHub登录页面进行身份验证。
成功登录后,用户将被重定向回你的应用程序,并且可以访问根路径("/"),返回"Hello, OAuth2!"。
这只是一个简单的入门例子,你可以根据自己的需求扩展和定制它。
参考资料
使用Oauth2实现微服务的安全保护
https://blog.csdn.net/j3T9Z7H/article/details/88016463
Spring Boot + Oauth2客户端凭据
我正在尝试使用带有客户端凭据流的Oath2在Spring Boot上保护我的微服务。
顺便说一句,那些微服务只会在中间件层上互相交谈,我的意思是不需要用户凭证即可进行授权(用户登录过程为Facebook)。
我在Internet上寻找了一些示例,这些示例显示了如何创建授权和资源服务器来管理此通信。但是,我只是找到了一些示例,说明了如何使用用户凭据(三段式)来执行此操作。
有人在Spring Boot和Oauth2中有任何示例吗?如果有可能提供有关所使用范围的更多详细信息,令牌交换将不胜感激。
Spring Boot 2.0.0 + OAuth2
如何解决Spring Boot 2.0.0 + OAuth2?
Spring Security 5使用现代化的密码存储,请参阅OAuth2 Autoconfig:
如果您使用自己的授权服务器配置通过
ClientDetailsServiceConfigurer
如下所示的实例配置有效客户端列表,请注意,此处配置的密码受Spring Security 5随附的现代化密码存储的约束。
要解决您的问题,请参阅Spring Security Reference:
当存储的密码之一没有ID(如“密码存储格式”一节中所述)时,会发生以下错误。
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped
for the id “null” at org.springframework.security.crypto.password.DelegatingPasswordEncoder$UnmappedIdPasswordEncoder.matches(DelegatingPasswordEncoder.java:233) at org.springframework.security.crypto.password.DelegatingPasswordEncoder.matches(DelegatingPasswordEncoder.java:196)
解决该错误的最简单方法是切换为显式提供
PasswordEncoder
密码进行编码的方式。解决此问题的最简单方法是弄清楚密码的当前存储方式,并明确提供正确的密码PasswordEncoder
。如果您是从Spring Security 4.2.x迁移的,则可以通过公开一个NoOpPasswordEncoder
bean 恢复到以前的行为。例如,如果您使用的是Java配置,则可以创建如下所示的配置:还原为
NoOpPasswordEncoder
不安全。您应该改为使用DelegatingPasswordEncoder
来支持安全密码编码。@Bean public static NoOpPasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); }
如果您使用的是XML配置,则可以公开
PasswordEncoder
带有id的passwordEncoder
:<b:bean id="passwordEncoder"https://www.jb51.cc/tag/ecurity/" target="_blank">ecurity.crypto.NoOpPasswordEncoder"
factory-method=”getInstance”/>
或者,您可以为所有密码加上正确的ID前缀,然后继续使用
DelegatingPasswordEncoder
。例如,如果您使用的是BCrypt,则可以从以下方式迁移密码:$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG
至
{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG
解决方法
Spring Boot 2 + Sping Security
OAuth2是否仍支持@AuthorizationServer
注释?通过阅读发行说明,还没有移植一些内容:
Oauth2支持
这是我的相关部分build.grade
:
验证服务器
// security
compile "org.springframework.boot:spring-boot-starter-security:${springBootVersion}"
// oauth
// https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2
compile "org.springframework.security.oauth:spring-security-oauth2:2.2.1.RELEASE"
客户端服务器
// support for Oauth2 user token services not yet migrated into Spring Boot 2.0
compile "org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.0.1.BUILD-SNAPSHOT"
而现在我的授权服务器的oauth2端点只返回一个401,当我试图通过一个客户端ID和客户端秘密为Basic
Authentication
对/oauth/token
。传递用户名和密码会给出不同的代码路径。因此,看起来OAuth过滤器的排列不完全。
是否有配置更新,或者我需要一组不同的gradle依赖项才能将Authorization Server恢复到以前的状态?
谢谢!
更新
我想结束这个问题的循环。除了加密客户端秘密。从Spring OAuth 2.3.2开始,RedisTokenStore问题也已解决:Spring
OAuth 2.3.2
Spring Boot 2.5.3 OAuth2 - Auth-Server 和 Webservice 分开,登录错误
如何解决Spring Boot 2.5.3 OAuth2 - Auth-Server 和 Webservice 分开,登录错误?
按照 https://developer.okta.com/blog/2019/03/12/oauth2-spring-security-guide 上的示例使用项目 Create an OAuth 2.0 Server
和 Build Your Client App
我无法让它正常运行。
我不使用 Thymeleaf
,因为我的 Web 服务返回的是数据,而不是页面。
OAuth 2.0 服务器项目
@SpringBootApplication
@EnableResourceServer
public class Demo2Application {
public static void main(String[] args) {
SpringApplication.run(Demo2Application.class,args);
}
}
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private final PasswordEncoder passwordEncoder;
public AuthorizationServerConfig(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("abcd")
.secret(passwordEncoder.encode("fDw7Mpkk5czHNuSRtmhGmAGL42CaxQB9"))
.authorizedGrantTypes("authorization_code")
.scopes("user_info")
.autoApprove(true)
.redirectUris("http://localhost:8082/login/oauth2/code/");
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");;
}
}
@Configuration
@Order(1)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login","/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("john")
.password(passwordEncoder().encode("doe"))
.roles("USER");
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@RestController
public class UserController {
@GetMapping("/user/me")
public Principal user(Principal principal) {
return principal;
}
}
application.properties
server.port=8090
pom.xml
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.5.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
我省略了项目最初使用的上下文路径。
网络服务项目
@RestController
public class MyRESTController {
@GetMapping("/securedPage")
public String securedPage(Principal principal) {
return "securedPage";
}
@GetMapping("/")
public String index(Principal principal) {
return "index";
}
}
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**").authorizeRequests()
.antMatchers("/","/login**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login();
}
}
application.properties
server.port=8082
server.servlet.session.cookie.name=UISESSION
spring.security.oauth2.client.registration.custom-client.client-id=abcd
spring.security.oauth2.client.registration.custom-client.client-secret=fDw7Mpkk5czHNuSRtmhGmAGL42CaxQB9
spring.security.oauth2.client.registration.custom-client.client-name=Auth Server
spring.security.oauth2.client.registration.custom-client.provider=custom-provider
spring.security.oauth2.client.registration.custom-client.scope=user_info
spring.security.oauth2.client.registration.custom-client.redirect-uri=http://localhost:8082/login/oauth2/code/
spring.security.oauth2.client.registration.custom-client.client-authentication-method=basic
spring.security.oauth2.client.registration.custom-client.authorization-grant-type=authorization_code
spring.security.oauth2.client.provider.custom-provider.authorization-uri=http://localhost:8090/oauth/authorize
spring.security.oauth2.client.provider.custom-provider.token-uri=http://localhost:8090/oauth/token
spring.security.oauth2.client.provider.custom-provider.user-info-uri=http://localhost:8090/user/me
spring.security.oauth2.client.provider.custom-provider.user-name-attribute=name
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
运行这两个项目时,在网络浏览器中使用 localhost:8082
我得到 index
作为响应。
使用 localhost:8082/securedPage
我被重定向到登录页面,输入用户名 john
和密码 doe
我得到以下错误页面:
Login with OAuth 2.0
[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource: 404 : [{"timestamp":"2021-07-30T07:58:54.529+00:00","status":404,"error":"Not Found","path":"/user/me"}]
Auth Server
不知道错误是什么引起的。看起来它与 OAuth 2.0 Server 项目中的 Webservice 应用程序属性和 UserController
的 URL 相关
spring.security.oauth2.client.provider.custom-provider.user-info-uri=http://localhost:8090/user/me
另外一个问题是: 可以避免登录表单吗?凭据以某种方式通过了。 如果客户端不是 Web 浏览器而是其他没有 UI 的应用程序。或者也许卷曲。我也有mockmvc测试,目前是Basic Auth,现在是OAuth2,会有什么影响?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
今天关于如何限制到特定域以使用Spring-Boot和OAuth2登录和限制指定ip访问的讲解已经结束,谢谢您的阅读,如果想了解更多关于OAuth2-03-springboot 整合、Spring Boot + Oauth2客户端凭据、Spring Boot 2.0.0 + OAuth2、Spring Boot 2.5.3 OAuth2 - Auth-Server 和 Webservice 分开,登录错误的相关知识,请在本站搜索。
本文标签: