Security-OAuth2.0 密码模式之客户端实现

我的OAuth2.0 客户端项目目录

 

pom 的配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>OauthText</artifactId>
        <groupId>OauthText</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>OAuthClient</artifactId>

     <dependencies>

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

     </dependencies>

</project>

核心配置UlegalZCConfiger

    @Bean
    public OAuth2RestOperations restTemplate() {
        AccessTokenRequest atr = new DefaultAccessTokenRequest();
        OAuth2RestTemplate template = new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
        ResourceOwnerPasswordAccessTokenProvider provider = new ResourceOwnerPasswordAccessTokenProvider();
        template.setAccessTokenProvider(provider);
        return template;
    }

    private ResourceOwnerPasswordResourceDetails resource() {
        ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
        resource.setClientId("000000");
        resource.setClientSecret("0000000");
        resource.setAccessTokenUri("http://192.168.100.1000:56/oauth/token");// Oauth2.0 服务端链接
        resource.setScope(Arrays.asList("read","write"));// 读写权限
        resource.setUsername("0000000");
        resource.setPassword("0000000");
        resource.setGrantType("password");// Oauth2.0 使用的模式 为密码模式
        return resource;
    }

 

 

  上图username 和password 要与服务端自定义验证的账户和密码相同。setClientId和setClientSecret要与服务端数据库配置一样。如下字段

 

 之后为前端拦截验证

package cn.xudy.sso.config;

import cn.xudy.sso.Tool.MyAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Created by Joe on 2017/8/8.
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启security注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Autowired
    private MyAuthenticationProvider provider;//自定义验证


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 全部通过
//        http.csrf().disable().authorizeRequests()
//                .anyRequest()
//                .permitAll();

        //允许所有用户访问"/"和"/home" 条件判断
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/login", "/page-login.html").permitAll()
                //其他地址的访问均需验证权限
                .antMatchers("/*.html").authenticated()
                .and()
                .formLogin()
                //指定登录页是"/login"
                .loginPage("/login")
                .defaultSuccessUrl("/otherPage")//登录成功后默认跳转到"/index.html"
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login")//退出登录后的默认url是"/login"
                .invalidateHttpSession(true)
                .permitAll();

    }
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        //将验证过程交给自定义验证工具
        auth.authenticationProvider(provider);
    }

}

 

 如果为条件验证,前端请求的话经过次方法,自定义验证代码WebSecurityConfig

 /**
     * 自定义验证方式
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        System.out.println("=-=-=-=-=:"+username);

          // 假装请求数据库

        User user=new User();


        Collection<? extends GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("USER");
        return new UsernamePasswordAuthenticationToken(user, password, authorities);
    }

    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }

 

 这是ClientControlled 请求

 

@RestController
public class ClientControlled {

    @Autowired
    private OAuth2RestOperations oauthRestTemplate;

    @PostMapping(value = "/login")
    public String  saveCuringEvidence(@RequestBody User user ){
        System.out.println("---------------------Client"+user.getUsername());
        //  重点请求服务端
        oauthRestTemplate.postForEntity("http://192.168.1.100:9595/log",user,String.class);

        return user.getUsername();
    }

}

 

 最后建议先看看我写的服务端 两方配套使用

 http://www.cnblogs.com/memoryXudy/p/7805178.html

posted @ 2017-11-08 17:32  Mr.DongYang  阅读(4515)  评论(2编辑  收藏  举报