Spring Security4 和 oauth2整合用户密码授权模式
上篇已经可以正常运行了,不过拿来测试还不够,下面介绍如何测试oauth2的用户密码模式,授权码模式下一篇说。
不想看这些乱七八糟的,可以直接把代码拉下来。
git地址:https://gitee.com/xiaoyaofeiyang/OauthUmp
spring Security4 和 oauth2整合 注解+xml混合使用(基础运行篇)
spring Security4 和 oauth2整合 注解+xml混合使用(进阶篇)
spring Security4 和 oauth2整合 注解+xml混合使用(授权码篇)
spring Security4 和 oauth2整合 注解+xml混合使用(注意事项篇)
spring Security4 和 oauth2整合 注解+xml混合使用(替换6位的授权码)
spring Security4 和 oauth2整合 注解+xml混合使用(替换用户名密码认证)
spring Security4 和 oauth2整合 注解+xml混合使用(验证码等额外数据验证)
测试API
新建个api,被oauth2保护
package com.ump.test.web;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ump.test.entity.WelEntity;
import com.ump.util.DateUtil;
@RestController("testApiController")
@RequestMapping("/api")
public class TestApiController {
@RequestMapping("/test")
public WelEntity test(@RequestParam String reqType){
String uuid = UUID.randomUUID().toString();
String welMsg = "welcome 程序猿";
if(reqType != null && "1000".equals(reqType)){
welMsg = "welcome 程序媛";
}
String dateTime = DateUtil.format(new Date(), DateUtil.SimpleDatePattern);
WelEntity welEntity = new WelEntity();
welEntity.setUuid(uuid);
welEntity.setDateTime(dateTime);
welEntity.setWelMsg(welMsg);
return welEntity;
}
@RequestMapping("/map")
public WelEntity testMap(@RequestParam Map map){
String uuid = UUID.randomUUID().toString();
System.out.println("map:"+map.values());
String reqMsg = (String) map.get("reqMsg");
String welMsg = "welcome 程序猿" + "----" + reqMsg;
String reqType = (String) map.get("reqType");
if(reqType != null && "1000".equals(reqType)){
welMsg = "welcome 程序媛";
}
String dateTime = DateUtil.format(new Date(), DateUtil.SimpleDatePattern);
WelEntity welEntity = new WelEntity();
welEntity.setUuid(uuid);
welEntity.setDateTime(dateTime);
welEntity.setWelMsg(welMsg);
return welEntity;
}
@RequestMapping("/ret")
public String testRet(){
String ret = "this is api";
return ret;
}
}
写一个测试页面
分别测试用户密码模式和授权码模式
jquery-3.2.1.min.js、jquery.cookie.js、base64.js搜一下就能搜到,这里就不提供了。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>
<script type="text/javascript" src="js/base64.js"></script>
<title>SkyNet</title>
</head>
<script type="text/javascript">
function ajaxTest() {
var type = "1001";
$.ajax({
type : "post",
url : "test/welCome",
dataType : "json",
data : {reqType : type} ,
success : function(data) {
$("#div1").html(data.uuid + "<br>" +
data.welMsg + "<br>"+
data.dateTime);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
function ajaxTest1() {
var type = "1001";
var reqMsg = "<h2>ak测试</h2><br>禁止访问";
var ak = $.cookie('ak') ;
$.ajax({
type : "post",
url : "api/map?access_token="+ak,
dataType : "json",
data : {"reqType" : type, "reqMsg" : reqMsg} ,
success : function(data) {
$("#div1").html(data.uuid + "<br>" +
data.welMsg + "<br>"+
data.dateTime);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
function ajaxTest2() {
$.cookie('ak', "");
$.cookie('code',"");
}
function ajaxTest3() {
var clientId = "my-trusted-client";
var redirectUrl = "http://127.0.0.1:9080/index.html";
var para = prompt("clientId#redirectUrl","MwonYjDKBuPtLLlK#http://127.0.0.1:9080/index.html");
var paraMap = para.split("#");
clientId = paraMap[0];
redirectUrl = paraMap[1];
console.log("参数:" + clientId + "---" + redirectUrl);
window.location.href = "oauth/authorize?client_id="
+clientId+"&response_type=code&scope=read&redirect_uri="
+redirectUrl;
}
function ajaxTest4() {
var para = prompt("clientId#redirectUrl","MwonYjDKBuPtLLlK#http://127.0.0.1:9080/index.html");
var paraMap = para.split("#");
clientId = paraMap[0];
redirectUrl = paraMap[1];
var code = $.cookie('code');
// var clientId = "my-trusted-client";
// var redirectUrl = "http://127.0.0.1:9080/index.html";
var client_secret="secret";
var grant_type="authorization_code";
//var su="TXdvbllqREtCdVB0TExsSzpzZWNyZXQ=";
var b = new Base64();
var su = b.encode(clientId+":"+client_secret);
console.log(su);
$.ajax({
type : "post",
url : "oauth/token",
dataType : "json",
data : {"client_id" : clientId, "client_secret" : client_secret,"grant_type" : grant_type, "redirect_uri" : redirectUrl,"code":code} ,
// beforeSend:function(xhr){
// xhr.setRequestHeader('Authorization', "Basic "+ su);
// },
success : function(data) {
$("#div4").html(data.access_token + "<br>" +
data.refresh_token + "<br>"+
data.expires_in);
$.cookie('ak', data.access_token);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
function ajaxTest5() {
$.ajax({
type : "post",
url : "/logout",
dataType : "text",
success : function(data) {
$("#div2").html("已登出");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
</script>
<body>
Hello World
<div id="div1"></div>
<div id="div2"></div>
<button type="button" onclick="ajaxTest()">Welcome</button> <button type="button" onclick="ajaxTest5()">登出去</button> <br><br>
<button type="button" onclick="ajaxTest1()">没授权测试</button> <button type="button" onclick="ajaxTest2()">清除ak</button><br><br>
<button type="button" onclick="window.location.href='auth.jsp?clientId=bXktdHJ1c3RlZC1jbGllbnQ6c2VjcmV0'">用户名密码模式</button><br><br>
<button type="button" onclick="ajaxTest3()">授权码模式</button>
<button type="button" onclick="ajaxTest4()">拿token</button>
<br>
<div id="div3"></div>
<div id="div4"></div>
<script type="text/javascript">
$(document).ready(function() {
$("#div1").html("呵呵");
var searchStr = location.search.substr(1);
if(searchStr){
var searchs = searchStr.split("&");
$("#div2").html("页面请求参数:" + searchs[0] + "和"+searchs[1] );
$.cookie('ak', searchs[0]);
$.cookie('rk', searchs[1]);
var code = searchs[0].split("=");
if(code.length == 2){
$("#div3").html("<h3>大爷终于拿到授权码了:" + code[1] +"</h3>");
$.cookie('code', code[1]);
$.cookie('ak', "");
$.cookie('rk', "");
}
}
});
</script>
</body>
</html>
auth.jsp
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<%@ page language="java" pageEncoding="UTF-8"%>
<head>
<%
String baseUrl = request.getContextPath();
String clientId = request.getParameter("clientId");
System.out.println("clientId:"+clientId );
String userName = request.getParameter("userName");
String userPwd = request.getParameter("userPwd");
if(userName == null || "".equals(userName)
||userPwd == null || "".equals(userPwd) ){
response.sendRedirect("/login.jsp?clientId="+clientId);
}
System.out.println(userName + "+++" +userPwd );
%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="<%=baseUrl%>/js/jquery-3.2.1.min.js"></script>
<title>SkyNet</title>
</head>
<script type="text/javascript">
function ajaxTest() {
var clientId = "<%=clientId%>";
var userName = "<%=userName%>";
var userPwd = "<%=userPwd%>";
$.ajax({
type : "post",
url : "<%=baseUrl%>/oauth/token",
dataType : "json",
data : {grant_type : "password",username : userName,password : userPwd} ,
beforeSend:function(xhr){
xhr.setRequestHeader('Authorization', "Basic "+ clientId);
},
success : function(data) {
window.location.replace("/index.html?"+data.access_token+"&"+data.refresh_token);
$("#div1").html(data.access_token + "<br>" +
data.refresh_token + "<br>"+
data.expires_in);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
function ajaxTest1() {
var type = "1";
$.ajax({
type : "post",
url : "<%=baseUrl%>/test/welCome",
dataType : "json",
data : {reqType : type} ,
success : function(data) {
$("#div1").html(data.uuid + "<br>" +
data.welMsg + "<br>"+
data.dateTime);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
</script>
<body>
这里是htm1
<div id="div1"></div>
<button type="button" onclick="ajaxTest1()">Welcome</button>
<button type="button" onclick="ajaxTest()">授权</button>
<script type="text/javascript">
$(document).ready(function() {
$("#div1").html("呵呵");
});
</script>
</body>
</html>
login.jsp
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<%@ page language="java" pageEncoding="UTF-8"%>
<head>
<%
String baseUrl = request.getContextPath();
String clientId = request.getParameter("clientId");
String clientPwd = request.getParameter("clientPwd");
System.out.println(clientId + "+++" +clientPwd );
%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="<%=baseUrl%>/js/jquery-3.2.1.min.js"></script>
<title>SkyNet</title>
</head>
<script type="text/javascript">
function ajaxTest() {
var type = "1";
$.ajax({
type : "post",
url : "<%=baseUrl%>/test/welCome",
dataType : "json",
data : {reqType : type} ,
success : function(data) {
$("#div1").html(data.uuid + "<br>" +
data.welMsg + "<br>"+
data.dateTime);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
</script>
<body>
这里是htm1
<div id="div1"></div>
<button type="button" onclick="ajaxTest()">Welcome</button>
<form action="<%=baseUrl%>/page/login" method="post">
<input type="hidden" name="clientId" value="<%=clientId%>">
First name:<br>
<input type="text" name="userName">
<br>
Last name:<br>
<input type="text" name="userPwd">
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#div1").html("呵呵");
});
</script>
</body>
</html>
page/login的controller
package com.ump.test.web;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.ump.test.entity.WelEntity;
import com.ump.util.DateUtil;
@Controller
@RequestMapping("/page")
public class TestRedirectController {
@RequestMapping("/test")
public String welCome(@RequestParam String reqType){
System.out.println(reqType);
return "/index"+reqType+".html";
}
@RequestMapping("/test1")
public String welCome1(@RequestParam String reqType){
System.out.println(reqType);
return "/index"+reqType+".jsp";
}
@RequestMapping("/login")
public String login(@RequestParam Map map){
System.out.println(map.values());
return "/auth.jsp?clientId="+map.get("clientId")+"&&clientPwd"
+map.get("clientPwd")+"&&userName="+map.get("userName")
+"&&userPwd="+map.get("userPwd");
}
}
这样基本上差不多了,后面说授权码模式了,这个用户名密码模式很没意思。