Spring相關(guān)之SpringSecurity使用(五)

JSONRespEntity

package com.lee.security.comoon;

/**
 * 
 * @ClassName: JSONRespEntity
 * @Description: 響應(yīng)實(shí)體
 */
public class JSONRespEntity<T>
{
    /**
     * 返回狀態(tài)碼 // 0代表成功,else失敗善延,建議用-1
     */
    private int status;

    /**
     * 返回實(shí)體
     */
    private T data;

    /**
     * 錯(cuò)誤描述
     */
    private String msg;

    /**
     * 默認(rèn)構(gòu)造器
     */
    public JSONRespEntity()
    {
        super();
    }

    /**
     * 只返回錯(cuò)誤信息
     * 
     * @param status
     */
    public JSONRespEntity(int status)
    {
        super();
        this.status = status;
    }

    /**
     * 返回錯(cuò)誤信息和描述
     * 
     * @param status
     * @param msg
     */
    public JSONRespEntity(int status, String msg)
    {
        super();
        this.status = status;
        this.msg = msg;
    }

    /**
     * 有參構(gòu)造
     * 
     * @param status
     *            狀態(tài)碼
     * @param data
     *            實(shí)體
     * @param msg
     *            錯(cuò)誤描述
     */
    public JSONRespEntity(int status, T data, String msg)
    {
        super();
        this.status = status;
        this.data = data;
        this.msg = msg;
    }

    /**
     * @return the status
     */
    public int getStatus()
    {
        return status;
    }

    /**
     * @param status
     *            the status to set
     */
    public void setStatus(int status)
    {
        this.status = status;
    }

    /**
     * @return the data
     */
    public T getData()
    {
        return data;
    }

    /**
     * @param data
     *            the data to set
     */
    public void setData(T data)
    {
        this.data = data;
    }

    /**
     * @return the msg
     */
    public String getMsg()
    {
        return msg;
    }

    /**
     * @param msg
     *            the msg to set
     */
    public void setMsg(String msg)
    {
        this.msg = msg;
    }

}

JsonResponse

package com.lee.security.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lee.security.comoon.JSONRespEntity;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  由于Response無(wú)法直接向客戶(hù)端 發(fā)送json 所以該工具類(lèi)使用objectMapper向前端書(shū)寫(xiě)json
 */
@Component
public class JsonResponse {

    public static Logger logger = Logger.getLogger(JsonResponse.class);

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 給客戶(hù)端返回json應(yīng)答
     *
     * @param resp
     * @param entity
     */
    public void writeJsonResponse(HttpServletResponse resp, JSONRespEntity entity)
    {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=UTF-8");
        try
        {
            objectMapper.writeValue(resp.getWriter(), entity);
        } catch (IOException e)
        {
            logger.error("轉(zhuǎn)換應(yīng)答實(shí)體為JSON格式時(shí)異常少态," + e.getMessage());
        }
    }

}

AccessDeniedHandler

package com.lee.security.springsecurity;

import com.lee.security.comoon.JSONRespEntity;
import com.lee.security.util.JsonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 授權(quán)失敗處理器
 */
@Component(value = "myAccessDeniedHandler")
public class MyAccessDeniedHandler implements AccessDeniedHandler
{
    @Autowired
    private JsonResponse jsonResponse;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException
    {
        JSONRespEntity<Object> entity = new JSONRespEntity<>();
        entity.setStatus(-998);
        entity.setMsg("無(wú)操作權(quán)限!");
        jsonResponse.writeJsonResponse(response,entity);
    }

}

AuthenticationEntryPoint

package com.lee.security.springsecurity;

import com.lee.security.comoon.JSONRespEntity;
import com.lee.security.util.JsonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 
 *         未登錄或session已失效
 */
@Component(value = "myAuthenticationEntryPoint")
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint
{

    @Autowired
    private JsonResponse jsonResponse;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException
    {
        JSONRespEntity<Object> entity = new JSONRespEntity<>();
        entity.setStatus(-997);
        entity.setMsg("請(qǐng)登錄系統(tǒng)!");
        jsonResponse.writeJsonResponse(response,entity);
    }

}

SimpleUrlAuthenticationFailureHandler

package com.lee.security.springsecurity;

import com.lee.security.comoon.JSONRespEntity;
import com.lee.security.util.JsonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 
 * 登錄失敗處理器
 *
 */
@Component(value = "myAuthenticationFailureHandler")
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private JsonResponse jsonResponse;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        JSONRespEntity<Object> entity = new JSONRespEntity<>();
        entity.setStatus(-1);
        entity.setMsg("登錄失敗!" + (exception.getMessage()));
        jsonResponse.writeJsonResponse(response,entity);
    }
}

SavedRequestAwareAuthenticationSuccessHandler


package com.lee.security.springsecurity;

import com.lee.security.comoon.JSONRespEntity;
import com.lee.security.util.JsonResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 認(rèn)證成功處理器
 *
 */
@Component(value = "myAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private static Logger logger = Logger.getLogger(MyAuthenticationSuccessHandler.class);

    @Autowired
    private JsonResponse jsonResponse;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication)  {
        //登錄成功后我們先拿到當(dāng)前登錄用戶(hù)的信息 共前臺(tái)使用
        MyAuthenticationToken authenticationToken = (MyAuthenticationToken) authentication;
        SpringSecurityUserInfo springSecurityUserInfo = authenticationToken.getSpringSecurityUserInfo();
        // 登錄成功后要返回的json
        JSONRespEntity<Object> entity = new JSONRespEntity<>();
        entity.setStatus(0);
        entity.setMsg("登錄成功!");
        entity.setData(springSecurityUserInfo);
        //這列將對(duì)當(dāng)前用戶(hù)信息 放心session redis 等等 比如說(shuō)移動(dòng)application.properties端的時(shí)候 以后做session共享等功能都可以在這里實(shí)現(xiàn)
        //這里我們將用戶(hù)信息直接放在security的上下文里面 后續(xù)業(yè)務(wù)需要使用的話(huà) 我們創(chuàng)建一個(gè)工具類(lèi)就可以直接拿出當(dāng)前用戶(hù)信息
        SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
        securityContext.setAuthentication(authentication);
        jsonResponse.writeJsonResponse(response,entity);
    }
}

LogoutHandler

package com.lee.security.springsecurity;

import com.lee.security.comoon.JSONRespEntity;
import com.lee.security.util.JsonResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component(value = "myLogoutHandler")
public class MyLogoutHandler implements LogoutHandler {

    public static Logger logger = Logger.getLogger(MyLogoutHandler.class);

    @Autowired
    private JsonResponse jsonResponse;

    @Override
    public void logout(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) {
        JSONRespEntity<Object> entity = new JSONRespEntity<>();
        entity.setStatus(0);
        entity.setMsg("已成功退出登錄!");
        jsonResponse.writeJsonResponse(resp,entity);
    }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市易遣,隨后出現(xiàn)的幾起案子彼妻,更是在濱河造成了極大的恐慌,老刑警劉巖训挡,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件澳骤,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡澜薄,警方通過(guò)查閱死者的電腦和手機(jī)为肮,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)肤京,“玉大人颊艳,你說(shuō)我怎么就攤上這事茅特。” “怎么了棋枕?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵白修,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我重斑,道長(zhǎng)兵睛,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任窥浪,我火速辦了婚禮祖很,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘漾脂。我一直安慰自己假颇,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布骨稿。 她就那樣靜靜地躺著笨鸡,像睡著了一般。 火紅的嫁衣襯著肌膚如雪坦冠。 梳的紋絲不亂的頭發(fā)上形耗,一...
    開(kāi)封第一講書(shū)人閱讀 51,301評(píng)論 1 301
  • 那天,我揣著相機(jī)與錄音蓝牲,去河邊找鬼趟脂。 笑死,一個(gè)胖子當(dāng)著我的面吹牛例衍,可吹牛的內(nèi)容都是我干的昔期。 我是一名探鬼主播,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼佛玄,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼硼一!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起梦抢,我...
    開(kāi)封第一講書(shū)人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤般贼,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后奥吩,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體哼蛆,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年霞赫,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了腮介。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡端衰,死狀恐怖叠洗,靈堂內(nèi)的尸體忽然破棺而出甘改,到底是詐尸還是另有隱情,我是刑警寧澤灭抑,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布十艾,位于F島的核電站,受9級(jí)特大地震影響腾节,放射性物質(zhì)發(fā)生泄漏忘嫉。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一禀倔、第九天 我趴在偏房一處隱蔽的房頂上張望榄融。 院中可真熱鬧,春花似錦救湖、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至耍铜,卻和暖如春邑闺,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背棕兼。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工陡舅, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人伴挚。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓靶衍,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親茎芋。 傳聞我的和親對(duì)象是個(gè)殘疾皇子颅眶,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容