Spring鉴权认证服务

本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

转载自夜明的孤行灯

本文链接地址: https://www.huangyunkun.com/2020/08/24/spring-auth-server-0-0-1/



Spring Security组件支持不同的鉴权认证方式,使用的时候一般是作为接入方来看的。如果要搭建自己的鉴权认证服务,Spring上周新推出的实验性项目Spring Authorization Server可以作为一个选择。

Spring Authorization Server支持以下标准

主要是支持Oauth2和JWT。

当然大部分实验性项目文档都不怎么完整,简单的例子使用如下。

主要分为auth server和resource server,当然还需要一个client。启动方式和普通Spring Boot应用类似,关注下Config即可

@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
public class AuthorizationServerConfig {

	// @formatter:off
	@Bean
	public RegisteredClientRepository registeredClientRepository() {
		RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
				.clientId("messaging-client")
				.clientSecret("secret")
				.clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
				.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
				.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
				.redirectUri("http://localhost:8080/authorized")
				.scope("message.read")
				.scope("message.write")
				.build();
		return new InMemoryRegisteredClientRepository(registeredClient);
	}
	// @formatter:on

	@Bean
	public KeyManager keyManager() {
		return new StaticKeyGeneratingKeyManager();
	}

	// @formatter:off
	@Bean
	public UserDetailsService users() {
		UserDetails user = User.withDefaultPasswordEncoder()
				.username("user1")
				.password("password")
				.roles("USER")
				.build();
		return new InMemoryUserDetailsManager(user);
	}
	// @formatter:on
}
@EnableWebSecurity
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {

	// @formatter:off
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.mvcMatcher("/messages/**")
				.authorizeRequests()
					.mvcMatchers("/messages/**").access("hasAuthority('SCOPE_message.read')")
					.and()
				.oauth2ResourceServer()
					.jwt();
	}
	// @formatter:on
}

目前jar包托管在spring仓库中,使用如下:

compile 'org.springframework.security.experimental:spring-security-oauth2-authorization-server:0.0.1'



本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

转载自夜明的孤行灯

本文链接地址: https://www.huangyunkun.com/2020/08/24/spring-auth-server-0-0-1/

发表评论