Spring Boot Oauth2.0授权服务器

[size=large][color=red][b]什么是OAuth?[/b][/color][/size]

[color=red][b]OAuth(Open Authorization,开放授权)是一个开放标准[/b][/color],允许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用。

HTTP基本认证是一种用来允许Web浏览器,或其他客户端程序在请求时提供以用户名和口令形式的凭证的登录方式。[color=red][b]用户名追加一个冒号然后串接上口令,得出的结果字符串再用Base64算法编码。例如,用户名是: admin,口令是: admin123,拼接后的结果是: admin:admin123,然后再用Base64编码,得到YWRtaW46YWRtaW4xMjM=。Base64编码的字符串发送出去,并由接收者解码,得到一个由冒号分隔的用户名和口令的字符串。[/b][/color]

[size=large][color=red][b]注意:用户名和密码在BaseClientDetails对象里面进行设置[/b][/color][/size]



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;


@Configuration
@EnableAuthorizationServer
public class AuthenticationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;

@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}

@Autowired
private ApiClientDetailsService apiClientDetailsService;

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("isAuthenticated()");
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(apiClientDetailsService);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore);
}
}



[size=large][color=red][b]设置基本认证所需要的用户名和密码[/b][/color][/size]


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Component
public class ApiClientDetailsService implements ClientDetailsService {

@Autowired
AppInfoRepository appInfoRepository;

@Autowired
JdbcTemplate jdbcTemplate;

@Override
public ClientDetails loadClientByClientId(String s) throws ClientRegistrationException {
// 用户名和密码都存在表中 查询表赋给appInfo对象

BaseClientDetails details = new BaseClientDetails();

details.setClientId(appInfo.getAppId());
details.setClientSecret(appInfo.getAppKey());
details.setAuthorizedGrantTypes(Arrays.asList("client_credentials"));
details.setAccessTokenValiditySeconds(7200);
details.setScope(roles);
details.setAuthorities(authorities);
details.setResourceIds(resources);

return details;
}

}



[size=large][color=blue][b]每次访问服务器需要从认证系统里面获得token值否则无法访问[/b][/color][/size]


//String clientReq = "appId:appKey";//默认客户端ID和客户端秘钥
String client_id="appId";//默认客户端ID
String client_secret = "appKey";//默认客户端秘钥
BASE64Encoder encoder = new BASE64Encoder();
BASE64Decoder decoder = new BASE64Decoder();
//String tokenUrl = "https://101.37.25.220:8091/oauth/token?grant_type=client_credentials&scope";
String tokenUrl = "https://localhost:8443/oauth/token";
HttpsGetData httpsGetData = new HttpsGetData();
List<String> list = new ArrayList<String>();
/**
* 获取返回的token
* 注:请求头为Authorization,值为Basic加空格加client_id:client_secret的Base64编码
*/
String tokenResult = httpsGetData.Do(tokenUrl+"?grant_type=client_credentials&scope","Authorization","Basic "+encoder.encode((client_id+":"+client_secret).getBytes()),"POST",null);
JSONObject tokenJSon = new JSONObject(tokenResult);//转成json数据
String token = tokenJSon.getString("access_token");// 获得的token值

// 具体请求数据用Bearer
httpsGetData.doGetData(resultUrl,"Authorization","Bearer "+token,"POST", paramJson.toString());



HttpsURLConnection connection = (HttpsURLConnection) realUrl.openConnection();
// 设置https相关属性
connection.setSSLSocketFactory(sc.getSocketFactory());
connection.setHostnameVerifier(new TrustAnyHostnameVerifier());
connection.setDoOutput(true);
connection.setDoInput(true);
// 设置通用的请求属性
connection.setRequestProperty("Content-Type", " application/json");
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty(hearderKey, headerValue);//基于base基本认证
connection.setRequestMethod(requestMethod);
// 建立实际的连接
connection.connect();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值