增加使用github登录

This commit is contained in:
zhou-hao
2017-12-01 20:18:23 +08:00
parent ef8b425205
commit c17a67bb6c
5 changed files with 167 additions and 79 deletions

View File

@@ -0,0 +1,75 @@
package org.hswebframework.web.example.oauth2;
import org.hswebframework.web.WebUtil;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.authorization.basic.web.SessionIdUserTokenGenerator;
import org.hswebframework.web.authorization.basic.web.UserTokenGenerator;
import org.hswebframework.web.authorization.oauth2.client.OAuth2RequestService;
import org.hswebframework.web.authorization.oauth2.client.listener.OAuth2CodeAuthBeforeEvent;
import org.hswebframework.web.authorization.oauth2.client.listener.OAuth2Listener;
import org.hswebframework.web.authorization.oauth2.client.request.OAuth2Session;
import org.hswebframework.web.authorization.simple.SimpleAuthentication;
import org.hswebframework.web.authorization.simple.SimplePermission;
import org.hswebframework.web.authorization.simple.SimpleRole;
import org.hswebframework.web.authorization.simple.SimpleUser;
import org.hswebframework.web.authorization.simple.builder.SimpleAuthenticationBuilder;
import org.hswebframework.web.authorization.simple.builder.SimpleDataAccessConfigBuilderFactory;
import org.hswebframework.web.authorization.token.UserTokenManager;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
public class GithubSSOAuthorizingListener
implements OAuth2Listener<OAuth2CodeAuthBeforeEvent> {
private OAuth2RequestService oAuth2RequestService;
private UserTokenManager userTokenManager;
private String userCenterServerId;
private String userAuthInfoApi = "/user";
public GithubSSOAuthorizingListener(OAuth2RequestService oAuth2RequestService, String userCenterServerId, UserTokenManager userTokenManager) {
this.oAuth2RequestService = oAuth2RequestService;
this.userCenterServerId = userCenterServerId;
this.userTokenManager = userTokenManager;
}
@Override
@SuppressWarnings("all")
public void on(OAuth2CodeAuthBeforeEvent event) {
String code = event.getCode();
Map<String, Object> userInfo = oAuth2RequestService
.create(userCenterServerId)
.byAuthorizationCode(code)
.authorize()
.request(userAuthInfoApi)
.get()
.as(Map.class);
String name = String.valueOf(userInfo.get("name"));
String id = String.valueOf(userInfo.get("id"));
String bio = String.valueOf(userInfo.get("bio"));
Authentication authentication = new SimpleAuthenticationBuilder(new SimpleDataAccessConfigBuilderFactory())
.user(SimpleUser.builder().username(bio).name(name).id("github-user:" + id).build())
.role(Arrays.asList(SimpleRole.builder().id("github-user").name("github用户").build()))
.permission(Arrays.asList(SimplePermission.builder().id("user-info").actions(new HashSet<>(Arrays.asList("get"))).build()))
.attributes((Map) userInfo)
.build();
MemoryAuthenticationManager.addAuthentication(authentication);
HttpSession session = WebUtil.getHttpServletRequest().getSession();
userTokenManager.signIn(session.getId(), UserTokenGenerator.TOKEN_TYPE_SESSION_ID, authentication.getUser().getId(), -1);
}
}

View File

@@ -0,0 +1,26 @@
package org.hswebframework.web.example.oauth2;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.authorization.AuthenticationManager;
import java.util.HashMap;
import java.util.Map;
public class MemoryAuthenticationManager implements AuthenticationManager {
static Map<String, Authentication> users = new HashMap<>();
public static void addAuthentication(Authentication authentication) {
users.put(authentication.getUser().getId(), authentication);
}
@Override
public Authentication getByUserId(String userId) {
return users.get(userId);
}
@Override
public Authentication sync(Authentication authentication) {
return authentication;
}
}

View File

@@ -18,16 +18,14 @@
package org.hswebframework.web.example.oauth2;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.authorization.AuthenticationManager;
import org.hswebframework.web.authorization.oauth2.client.OAuth2RequestService;
import org.hswebframework.web.authorization.oauth2.client.request.OAuth2Session;
import org.hswebframework.web.authorization.oauth2.client.response.OAuth2Response;
import org.hswebframework.web.authorization.oauth2.client.OAuth2ServerConfig;
import org.hswebframework.web.authorization.oauth2.client.simple.OAuth2ServerConfigRepository;
import org.hswebframework.web.authorization.oauth2.client.simple.provider.github.GithubResponseConvert;
import org.hswebframework.web.authorization.oauth2.client.simple.provider.github.GithubResponseJudge;
import org.hswebframework.web.authorization.token.UserTokenManager;
import org.hswebframework.web.commons.entity.DataStatus;
import org.hswebframework.web.commons.entity.factory.EntityFactory;
import org.hswebframework.web.entity.oauth2.client.OAuth2ServerConfigEntity;
import org.hswebframework.web.service.oauth2.client.OAuth2ServerConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
@@ -37,9 +35,6 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import java.util.HashMap;
import java.util.Map;
/**
* TODO 完成注释
*
@@ -56,63 +51,71 @@ public class OAuth2ClientApplication implements CommandLineRunner {
}
@Bean
public AuthenticationManager authenticationManager() {
// 由于没有使用用户管理,
// 而且暂时没有实现默认的OAuth2相关的权限获取策略,
// 所以这里使用通过OAuth2进行获取
// 实现类似sso的功能,这里实际上应该将权限信息存储起来
Map<String, OAuth2Session> sessionMap = new HashMap<>();
public GithubResponseConvert githubResponseConvert() {
return new GithubResponseConvert();
}
return new AuthenticationManager() {
@Override
public Authentication getByUserId(String userId) {
//获取远程的用户权限信息
return sessionMap.computeIfAbsent("auth", key -> oAuth2RequestService.create("hsweb-oauth-server")
.byClientCredentials())
.request("oauth2/user-auth-info/" + userId)
.get().onError(OAuth2Response.throwOnError)
.as(Authentication.class);
}
@Bean
public GithubResponseJudge githubResponseJudge() {
return new GithubResponseJudge();
}
@Override
public Authentication sync(Authentication authentication) {
//暂时不支持
return authentication;
}
};
@Bean
public MemoryAuthenticationManager memoryAuthenticationManager() {
return new MemoryAuthenticationManager();
}
@Autowired
EntityFactory entityFactory;
EntityFactory entityFactory;
@Autowired
OAuth2ServerConfigService serverConfigService;
OAuth2ServerConfigRepository repository;
@Autowired
OAuth2RequestService oAuth2RequestService;
OAuth2RequestService oAuth2RequestService;
@Autowired
UserTokenManager userTokenManager;
@Override
public void run(String... strings) throws Exception {
OAuth2ServerConfigEntity entity = entityFactory.newInstance(OAuth2ServerConfigEntity.class);
entity.setId("hsweb-oauth-server");
entity.setName("hsweb OAuth2");
//可以修改hosts文件改为域名
entity.setApiBaseUrl("http://localhost:8080/");
entity.setAuthUrl("oauth2/login.html");
entity.setAccessTokenUrl("oauth2/token");
//和服务端创建的一致
entity.setClientId("hsweb_oauth2_example");
entity.setClientSecret("hsweb_oauth2_example_secret");
entity.setRedirectUri("http://localhost:8808/");
//hsweb
entity.setProvider("hsweb");
entity.setStatus(DataStatus.STATUS_ENABLED);
//add
serverConfigService.insert(entity);
//github
OAuth2ServerConfig github = OAuth2ServerConfig.builder()
.id("github")
.name("github test")
.clientId("b9cd11eae646a5a5c4bf")
.clientSecret("6b664ebfc051f5919589ccd20cc9e774b026f6f5")
.apiBaseUrl("https://api.github.com/")
.authUrl("https://github.com/login/oauth/authorize")
.accessTokenUrl("https://github.com/login/oauth/access_token")
.redirectUri("http://localhost:8808/")
.provider("github")
.status(DataStatus.STATUS_ENABLED)
.build();
repository.save(github);
OAuth2SSOAuthorizingListener listener = new OAuth2SSOAuthorizingListener(oAuth2RequestService, entity.getId(),userTokenManager);
oAuth2RequestService.registerListener(entity.getId(), listener);
OAuth2ServerConfig hsweb = OAuth2ServerConfig.builder()
.id("hsweb-oauth-server")
.name("hsweb OAuth2")
.clientId("hsweb_oauth2_example")
.clientSecret("hsweb_oauth2_example_secret")
.apiBaseUrl("http://localhost:8080/")
.authUrl("oauth2/login.html")
.accessTokenUrl("oauth2/token")
.redirectUri("http://localhost:8808/")
.provider("hsweb")
.status(DataStatus.STATUS_ENABLED)
.build();
repository.save(hsweb);
OAuth2SSOAuthorizingListener listener = new OAuth2SSOAuthorizingListener(oAuth2RequestService, hsweb.getId(), userTokenManager);
GithubSSOAuthorizingListener githubSSOAuthorizingListener =
new GithubSSOAuthorizingListener(oAuth2RequestService, github.getId(), userTokenManager);
oAuth2RequestService.registerListener(hsweb.getId(), listener);
oAuth2RequestService.registerListener(github.getId(), githubSSOAuthorizingListener);
}

View File

@@ -70,8 +70,10 @@ public class OAuth2SSOAuthorizingListener
.get().onError(OAuth2Response.throwOnError)
.as(Authentication.class);
HttpSession httpSession = WebUtil.getHttpServletRequest()
.getSession();
//添加用户信息
MemoryAuthenticationManager.addAuthentication(authentication);
HttpSession httpSession = WebUtil.getHttpServletRequest().getSession();
userTokenManager.signIn(httpSession.getId(), "sessionId",authentication.getUser().getId(), 60 * 60 * 1000L);

View File

@@ -25,26 +25,20 @@
<script type="application/javascript" src="//cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<button onclick="doHswebLogin()">使用hsweb登录</button>
<body style="text-align: center">
<button onclick="doOAuth2Login('hsweb-oauth-server')">使用hsweb登录</button>&nbsp;&nbsp;
<button onclick="doOAuth2Login('github')">使用github登录</button>
</body>
</html>
<script type="text/javascript">
function doHswebLogin() {
function doOAuth2Login(provider) {
var uri = getRequest()["redirect"];
if (!uri) uri = "/";
window.open('/oauth2/boot/hsweb-oauth-server?redirect=' + uri);
var principal = "hsweb_oauth2_example";
// var api = "http://localhost:8080/oauth2/login.html";
// //申请一个state
// doAjax("GET", "/oauth2/state", {}, function (e) {
// if (e) {
// window.open(api + "?client_id=" + principal + "&response_type=code&state=" + e.result + "&redirect_uri="
// + escape("http://localhost:8808/oauth2/callback/hsweb-oauth-server/?redirect=" + uri))
// }
// });
window.open('/oauth2/boot/' + provider + '?redirect=' + uri);
}
function getRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
@@ -58,16 +52,4 @@
return theRequest;
}
function doAjax(method, url, data, success, error) {
$.ajax({
type: method,
url: url,
data: data,
success: success,
error: function (e) {
error(e.responseJSON);
},
dataType: "json"
});
}
</script>