1. 程式人生 > >spring Security4 和 oauth2整合 註解+xml混合使用(進階篇)

spring Security4 和 oauth2整合 註解+xml混合使用(進階篇)

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");
    }
}

這樣基本上差不多了,後面說授權碼模式了,這個使用者名稱密碼模式很沒意思。