H. *_*ock 1 single-sign-on jwt spring-boot api-gateway
我想用Gradle,Spring Boot2,Zuul,JWT,带有REST-Api的微服务和自制认证服务器来设置SSO微服务环境.当身份验证服务器,网关和微服务充当OAuth客户端和资源服务器时,它们的注释是什么?什么是最小化设置?
对于gradle配置,我建议使用网站http://start.spring.io/和授权服务器.配置将是这样的:
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Finchley.RELEASE'
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.cloud:spring-cloud-starter-oauth2')
compile('org.springframework.cloud:spring-cloud-starter-security')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
Run Code Online (Sandbox Code Playgroud)
然后auth服务器将是这样的:
@Configuration
@EnableAuthorizationServer
public class SecurityOAuth2AutorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private final AccountUserDetailsService accountUserDetailsService;
private final UserDetailsService authenticationManager;
private final PasswordEncoder passwordEncoder;
public SecurityOAuth2AutorizationServerConfig(UserDetailsService accountUserDetailsService,
AuthenticationManager authenticationManager,
PasswordEncoder passwordEncoder) {
this.accountUserDetailsService = accountUserDetailsService;
this.authenticationManager = authenticationManager;
this.passwordEncoder = passwordEncoder;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.approvalStoreDisabled()
.authenticationManager(authenticationManager)
.tokenStore(tokenStore())
.accessTokenConverter(accessTokenConverter())
.userDetailsService(accountUserDetailsService)
.reuseRefreshTokens(false);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("permitAll()")
.passwordEncoder(passwordEncoder)
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret(passwordEncoder.encode("secret"))
.authorizedGrantTypes("authorization_code", "refresh_token", "password").scopes("openid")
.authorities("ROLE_USER", "ROLE_EMPLOYEE")
.scopes("read", "write", "trust", "openid")
.resourceIds("oauth2-resource")
.autoApprove(true)
.accessTokenValiditySeconds(5)
.refreshTokenValiditySeconds(60*60*8);
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
....
}
}
Run Code Online (Sandbox Code Playgroud)
sso登录页面的配置如下:
@Configuration
@Order(SecurityProperties.DEFAULT_FILTER_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.formLogin()
.permitAll()
.and()
.authorizeRequests().anyRequest().authenticated();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public UserDetailsService accountUserDetailsService() {
InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
inMemoryUserDetailsManager.createUser(new User("user", "secret",
Collections.singleton(new SimpleGrantedAuthority("USER"))));
return inMemoryUserDetailsManager;
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
Run Code Online (Sandbox Code Playgroud)
在您的sso应用程序中,您可以进行如下配置:
@EnableOAuth2Sso
@EnableZuulProxy
@SpringBootApplication
public class SsoDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SsoDemoApplication.class, args);
}
@Bean
@Primary
public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ClientContext context,
OAuth2ProtectedResourceDetails authorizationCodeResourceDetails) {
return new OAuth2RestTemplate(authorizationCodeResourceDetails, context);
}
}
Run Code Online (Sandbox Code Playgroud)
在你的application.yml中:
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/singin
clientAuthenticationScheme: form
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
......
-----END PUBLIC KEY-----
server:
use-forward-headers: true
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
your-service: /your-service/**
proxy:
auth:
routes:
spent-budget-service: oauth2
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以使用auth服务器在sso中配置客户端应用程序,@ EnableOAuth2Sso将为您做任何事情,它也像客户端应用程序,如果您的应用程序未经过身份验证,您的sso会将您重定向到您的auth服务器的登录页面并将为您更新您的令牌zuul令牌中继它也可用作此用例中的功能我使用eureka作为发现服务注册表.配置OAuth2RestTemplate非常重要,因为spring将使用此bean自动为您刷新令牌,否则一旦令牌过期,您将无法自动刷新令牌.
你的所有资源服务器都是这样的:
@EnableResourceServer
@SpringBootApplication
public class AccountServiceApplication {
public static void main(String[] args) {
SpringApplication.run(AccountServiceApplication.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
在你的application.yml中:
security:
oauth2:
resource:
jwt:
key-value: -----BEGIN PUBLIC KEY-----
.....
-----END PUBLIC KEY----
Run Code Online (Sandbox Code Playgroud)
-
当然这是非常小的配置,但足够的id只是为了开始
更新:
不要忘记网关,sso和任何其他资源服务器上的应用程序yml中的资源配置,否则将无法针对您的auth服务器验证令牌.
如果是普通的oauth2令牌,你可以使用
security.oauth2.resource.token-info-uri: your/auth/server:yourport/oauth/check_token
Run Code Online (Sandbox Code Playgroud)
要么
security.oauth2.resource.user-info-uri: yourAccountDEtailsRndpoint/userInfo.json
security.oauth2.resource.preferTokenInfo: false
Run Code Online (Sandbox Code Playgroud)
在preferTokenInfo:false的情况下,您在auth服务器上的典型帐户数据入口.
@RestController
@RequestMapping("/account")
class UserRestFullEndPoint {
@GetMapping("/userInfo")
public Principal userInfo(Principal principal){
return principal;
}
}
Run Code Online (Sandbox Code Playgroud)
在token-info-uri配置的情况下,UserInfoRestTemplateFactory将由spring自动提供,唯一要记住的是配置Oauth2RestTemplate,否则您的令牌将不再刷新
更新2
如果是非JWT令牌,则缺少的配置是在auth服务器上添加@EnableResourceServer.
通过这种方式,您的用户信息uri将返回主要对象,例如json.问题是你的端点在任何情况下都会返回null,因此你的服务收到401.这是因为你的auth服务器只能返回令牌而不能暴露其他不是框架端点的服务才能提供令牌.由于您需要返回用户信息,因此需要一种公开资源的方法,因此您需要公开auth服务器,即使资源服务器也是如此.在jwt的情况下,它是无用的,因为令牌验证和用户信息将由令牌本身提供.用户信息将由jwt提供,并由jwt密钥验证.
恢复您的auth服务器将如下所示:
@SpringBootApplication
public class AuthserverApplication {
public static void main(String[] args) {
SpringApplication.run(AuthserverApplication.class, args);
}
}
@RestController
class UserInfo {
@GetMapping("/account/user-info")
public Principal principal(Principal principal){
System.out.println(principal);
return principal;
}
}
@Controller
class Login{
@GetMapping(value = "/login", produces = "application/json")
public String login(){
return "login";
}
}
@Configuration
@EnableAuthorizationServer
@EnableResourceServer
class SecurityOAuth2AutorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.authenticationManager(authenticationManager)
.approvalStoreDisabled()
.reuseRefreshTokens(false)
.userDetailsService(accountUserDetailsService());
}
@Bean
public UserDetailsService accountUserDetailsService() {
InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
inMemoryUserDetailsManager.createUser(new User("user", passwordEncoder.encode("secret"),
Collections.singleton(new SimpleGrantedAuthority("USER"))));
return inMemoryUserDetailsManager;
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("permitAll()")
.passwordEncoder(passwordEncoder)
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret(passwordEncoder.encode("secret"))
.authorizedGrantTypes("client_credentials", "password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_USER", "ROLE_EMPLOYEE")
.scopes("read", "write", "trust", "openid")
.autoApprove(true)
.refreshTokenValiditySeconds(20000000)
.accessTokenValiditySeconds(20000000);
}
}
@Configuration
@Order(SecurityProperties.DEFAULT_FILTER_ORDER)
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().httpBasic().disable()
.formLogin().loginPage("/login").loginProcessingUrl("/login")
.permitAll()
.and()
.requestMatchers().antMatchers("/account/userInfo", "/login", "/oauth/authorize", "/oauth/confirm_access")
.and()
.authorizeRequests().anyRequest().authenticated();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
Run Code Online (Sandbox Code Playgroud)
登录页面:
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap.css}"/>
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap-theme.css}"/>
<title>Log In</title>
</head>
<body>
<div class="container">
<form role="form" action="login" method="post">
<div class="row">
<div class="form-group">
<div class="col-md-6 col-lg-6 col-md-offset-2 col-lg-offset-">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username"/>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-6 col-lg-6 col-md-offset-2 col-lg-offset-2">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password"/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-lg-offset-2 col-lg-12">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
<script th:src="@{/webjars/jquery/3.2.0/jquery.min.js}"></script>
<script th:src="@{/webjars/bootstrap/3.3.7-1/js/bootstrap.js}" ></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
application.yml:
server:
use-forward-headers: true
port: 9090
servlet:
context-path: /auth
management.endpoints.web.exposure.include: "*"
spring:
application:
name: authentication-server
Run Code Online (Sandbox Code Playgroud)
你的sso服务器将如下所示:
@EnableZuulProxy
@SpringBootApplication
public class SsoApplication {
public static void main(String[] args) {
SpringApplication.run(SsoApplication.class, args);
}
@Bean
public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ClientContext context,
OAuth2ProtectedResourceDetails authorizationCodeResourceDetails) {
return new OAuth2RestTemplate(authorizationCodeResourceDetails, context);
}
}
@Configuration
@EnableOAuth2Sso
class OAuth2SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().cors().and().httpBasic().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.authorizeRequests().anyRequest().authenticated();
}
}
Run Code Online (Sandbox Code Playgroud)
http:// localhost:8080/index.html上的简单页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
It Works by an SSO
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$.ajax({
url: "/hello-service/hello",
success: function (data, status) {
window.alert("The returned data" + data);
}
})
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
application.yml:
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:9090/auth/oauth/token
userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
auto-approve-scopes: '.*'
registered-redirect-uri: http://localhost:9090/auth/login
clientAuthenticationScheme: form
resource:
user-info-uri: http://localhost:9090/auth/account/user-info
prefer-token-info: false
management.endpoints.web.exposure.include: "*"
server:
use-forward-headers: true
port: 8080
zuul:
sensitiveHeaders:
ignoredServices: '*'
ignoreSecurityHeaders: false
addHostHeader: true
routes:
hello-service:
serviceId: hello-service
path: /hello-service/**
url: http://localhost:4040/
proxy:
auth:
routes:
hello-service: oauth2
Run Code Online (Sandbox Code Playgroud)
你的hello服务(resourceserver)将是:
@SpringBootApplication
public class ResourceServerApplication {
public static void main(String[] args) {
SpringApplication.run(ResourceServerApplication.class, args);
}
}
@RestController
class HelloService {
@GetMapping("/hello")
public ResponseEntity hello(){
return ResponseEntity.ok("Hello World!!!");
}
}
@Configuration
@EnableResourceServer
class SecurityOAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().authenticated()
.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
Run Code Online (Sandbox Code Playgroud)
我希望它对你有用
| 归档时间: |
|
| 查看次数: |
445 次 |
| 最近记录: |