我的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

Security-OAuth2.0 密码模式之客户端实现的更多相关文章

  1. oauth2.0密码模式详解

    oauth2.0密码模式 欢迎关注博主公众号「Java大师」, 专注于分享Java领域干货文章http://www.javaman.cn/sb2/oauth-password 如果你高度信任某个应用, ...

  2. Spring Security OAuth2 Demo —— 密码模式(Password)

    前情回顾 前几节分享了OAuth2的流程与授权码模式和隐式授权模式两种的Demo,我们了解到授权码模式是OAuth2四种模式流程最复杂模式,复杂程度由大至小:授权码模式 > 隐式授权模式 > ...

  3. IdentityServer4:IdentityServer4+API+Client+User实践OAuth2.0密码模式(2)

    一.密码模式实操 仍然使用第一节的代码:做如下改动: 1.授权服务端 前面我们使用项目:Practice.IdentityServer作为授权服务器 修改项目的Config.cs类: 添加测试用户,并 ...

  4. webapi之owin的oauth2.0密码模式_01概述

    一般在webapi接口中,为了防止接口被随意调用,都会验证用户身份. 然而不能每次调用接口都需要用户输入用户名密码来验证,这时就需要授权颁发令牌了,持有令牌就可以访问接口,接口也能验证令牌身份. 简单 ...

  5. springboot+spring security +oauth2.0 demo搭建(password模式)(认证授权端与资源服务端分离的形式)

    项目security_simple(认证授权项目) 1.新建springboot项目 这儿选择springboot版本我选择的是2.0.6 点击finish后完成项目的创建 2.引入maven依赖  ...

  6. 基于spring boot2.0+spring security +oauth2.0+ jwt微服务架构

    github地址:https://github.com/hankuikuide/microservice-spring-security-oauth2 项目介绍 该项目是一个演示项目,主要演示了,基于 ...

  7. Spring Cloud Security OAuth2.0 认证授权系列(一) 基础概念

    世界上最快的捷径,就是脚踏实地,本文已收录[架构技术专栏]关注这个喜欢分享的地方. 前序 最近想搞下基于Spring Cloud的认证授权平台,总体想法是可以对服务间授权,想做一个基于Agent 的无 ...

  8. Spring Security OAuth2.0认证授权二:搭建资源服务

    在上一篇文章[Spring Security OAuth2.0认证授权一:框架搭建和认证测试](https://www.cnblogs.com/kuangdaoyizhimei/p/14250374. ...

  9. Spring Security OAuth2.0认证授权四:分布式系统认证授权

    Spring Security OAuth2.0认证授权系列文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授 ...

随机推荐

  1. python之daemon线程

    [python之daemon线程] A thread can be flagged as a “daemon thread”. The significance of this flag is tha ...

  2. JSONArray的初始化的形式

    1 转义字符形式 [    {        \"ID\": \"1900036295\",        \"DEPT\": \" ...

  3. web和wap网站的区别 (转)

    WAP的全称是“无线应用协议(Wireless Application Protocol)”,是一种向移动终端提供互联网内容和先进增值服务的全球统一的开放式协议标准, 是简化了的无线Internet ...

  4. gRPC初探——概念介绍以及如何构建一个简单的gRPC服务

    目录 引言 1. gRPC简介 2. 使用Protocol Buffers进行服务定义 2.1 定义消息 2.2 定义服务接口 3.构建简单的gRPC服务 3.1 编写proto文件,定义消息和接口 ...

  5. assetBundle打包脚本与LUA

    AssetBundles与脚本 所有Unity的AssetBundle,无论是从本地获取 还是www,或者打包整个场景.物体上的脚本都不会被编译.所以AssetBundle打包的时候即使物体上有脚本. ...

  6. js获取不到动态添加的标签的值的解决方法

    遇到了js无法获得动态添加的标签的值,百度了一番,最后自己解决了问题,但是原理现在还不怎么明确. $("input[id='txtAttValue']").each(functio ...

  7. React Native开源项目案例

    (六).React Native开源项目: 1.Pober Wong_17童鞋为gank.io做的纯React Native项目,开源地址:https://github.com/Bob1993/Rea ...

  8. c++ stringstream的使用

    stringstream ss;//一次创建多次使用,需要进行clear()操作清除流状态标记 int i=0; while (i<3) { ss<<"21"; ...

  9. 同台机器2个网卡配置同段IP

    看个例子:1.on serverifconfig eth4 192.168.1.10/24 upifconfig eth5 192.168.1.11/24 up2.on clientifconfig ...

  10. [Training Video - 2] [Java Introduction] [Install Java and Eclipse, Create Class]

    Download Java : https://java.com/en/download/ Download Eclipse : https://www.eclipse.org/downloads/ ...