Spring boot for Eclipse 开发指南第六节 Oauth 2.0

 折腾了一天. 终于在晚上 7点半 搞定了

1.废话不说 pom.xml 增加依赖 主要就是security 和 oauth2.0 的包

        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
		
		<!-- security oauth2 -->
		<dependency>
	        <groupId>org.springframework.cloud</groupId>
	        <artifactId>spring-cloud-starter-oauth2</artifactId>
		</dependency>

2.继承 WebSecurityConfigurerAdapter 的配置类中 主配置文件

    @Override  
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {  
        auth.inMemoryAuthentication().withUser("shili").password("zzz123").roles("ADMIN");  
    }  
@Override  
    protected void configure(HttpSecurity http) throws Exception {  
    	http.csrf().disable()
		.anonymous().disable()
	  	.authorizeRequests()
	  	.antMatchers("/oauth/token").permitAll().and().formLogin();
    }

这里主要配置了登录的用户名和密码 以及 开放 /oauth/token 的路径

3. 继承 ResourceServerConfigurerAdapter 的配置类中  

@Configuration
@EnableResourceServer
@Order(6)
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
	
	private static final String RESOURCE_ID = "my_rest_api";
	
	@Override
	public void configure(ResourceServerSecurityConfigurer resources) {
		resources.resourceId(RESOURCE_ID).stateless(false);
	}

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.
		anonymous().disable()
		.requestMatchers().antMatchers("/sayhello")
		.and().authorizeRequests()
		.antMatchers("/sayhello").access("hasRole('ADMIN')")
		.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());		 
	}
}

4.最后是继承 AuthorizationServerConfigurerAdapter 的配置类

@Configuration
@EnableAuthorizationServer
public class SecurityOauth2Config extends AuthorizationServerConfigurerAdapter {
	
	private static String REALM="MY_OAUTH_REALM";
		
	@Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		//客户端详情服务
		clients.inMemory()
        .withClient("13890999")
        .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
        .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
        .scopes("read", "write", "trust")
        .secret("secret")
        .accessTokenValiditySeconds(120).//Access token is only valid for 2 minutes.
        refreshTokenValiditySeconds(600);//Refresh token is only valid for 10 minutes.
	}
	
    @Override  
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {  
        oauthServer.allowFormAuthenticationForClients();  
    }  
}

5.测试步骤 首先访问以下地址

http://localhost:8080/oauth/authorize?client_id=13890999&response_type=code&redirect_uri=http://localhost:8080

就会跳转到登录页面 然后登录 会跳转到授权确认页面 最后会跳转到 http://localhost:8080/code=XXXXX

其中的XXXXX就是我们需要的code

然后使用curl开始POST我们的token 地址

curl "http://localhost:8080/oauth/token" -d "client_id=13890999&client_secret=secret&grant_type=authorization_code&code=XXXXX&redirect_uri=http://localhost:8080"

命令中的CODE 你要修改成你上一步获取到CODE

他就会返回如下 代码 表示已经成功了!

{"access_token":"5905c5da-0925-4752-8b6a-423936cfac71","token_type":"bearer","re
fresh_token":"9ebff67a-8a1d-462c-bf74-4a0a66f2980b","expires_in":119,"scope":"tr
ust read write"}

有了这个access_token 就可以访问 ResourceServerConfigurerAdapter 配置的url了

curl "http://localhost:8080/sayhello" -d "access_token=5905c5da-
0925-4752-8b6a-423936cfac71" -v

出现网页源代码 表示访问成功 到这里 Auth2.0 完成了一半了

明天 把那个很丑的授权页改一改 就OK了

作者:施立

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OAuth2.0是一种常用的认证授权机制,Spring Security是Spring框架中的安全模块,可以实现OAuth2.0认证。本文将介绍如何利用Spring Boot 2.0Spring Security实现简单的OAuth2.0认证方式1。 1. 添加依赖 在项目的pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.7.RELEASE</version> </dependency> ``` 其中,spring-boot-starter-security是Spring Boot中包含Spring Security的依赖,spring-security-oauth2是Spring Security中实现OAuth2.0的依赖。 2. 配置Spring Security 在Spring Boot应用中,可以通过application.properties或application.yml文件来配置Spring Security。在本文中,我们将使用application.yml文件来配置Spring Security。 ``` spring: security: oauth2: client: registration: custom-client: client-id: custom-client-id client-secret: custom-client-secret authorization-grant-type: authorization_code redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}' scope: - read - write provider: custom-provider: authorization-uri: https://custom-provider.com/oauth2/auth token-uri: https://custom-provider.com/oauth2/token user-info-uri: https://custom-provider.com/userinfo user-name-attribute: sub ``` 其中,我们定义了一个名为custom-client的OAuth2.0客户端,它的客户端ID和客户端密钥分别为custom-client-id和custom-client-secret,授权方式为authorization_code,重定向URI为{baseUrl}/login/oauth2/code/{registrationId},授权范围为read和write。 同时,我们定义了一个名为custom-provider的OAuth2.0提供者,它的授权URI、令牌URI、用户信息URI和用户名属性分别为https://custom-provider.com/oauth2/auth、https://custom-provider.com/oauth2/token、https://custom-provider.com/userinfo和sub。 3. 配置OAuth2.0登录 在Spring Security中,可以通过配置HttpSecurity对象来定义登录、授权等行为。在本文中,我们将使用configure方法来配置HttpSecurity对象。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .oauth2Login() .loginPage("/login") .defaultSuccessURL("/dashboard") .and() .logout() .logoutSuccessUrl("/") .permitAll(); } } ``` 其中,我们使用了authorizeRequests方法来设置授权规则,任何请求都需要进行认证,除了根路径和home路径。我们还使用了oauth2Login方法来设置OAuth2.0登录的相关配置,包括登录页面、默认成功URL等。最后,我们使用了logout方法来设置登出的相关配置,包括成功URL等。 4. 配置用户信息 在OAuth2.0认证中,用户信息通常由OAuth2.0提供者来维护。在Spring Security中,可以通过实现UserInfoRestTemplateFactory接口来获取用户信息。 ``` @Configuration public class OAuth2Config { @Bean public OAuth2UserService<OAuth2UserRequest, OAuth2User> oAuth2UserService() { return new DefaultOAuth2UserService(); } @Bean public UserInfoRestTemplateFactory userInfoRestTemplateFactory() { return new CustomUserInfoRestTemplateFactory(); } } ``` 其中,我们使用了DefaultOAuth2UserService来获取用户信息,同时使用了CustomUserInfoRestTemplateFactory来创建RestTemplate对象。 5. 编写测试 最后,我们可以编写一个简单的测试来验证OAuth2.0认证是否生效。 ``` @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc public class OAuth2Test { @Autowired private MockMvc mockMvc; @Test public void testOAuth2Login() throws Exception { mockMvc.perform(get("/login")) .andExpect(status().isOk()) .andExpect(content().string(containsString("Login with custom-provider"))) .andReturn(); } } ``` 在测试中,我们使用MockMvc对象模拟访问/login路径,期望返回200状态码,并且页面内容中包含“Login with custom-provider”的字符串。 至此,我们已经成功地利用Spring Boot 2.0Spring Security实现了简单的OAuth2.0认证方式1。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值