久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

Springboot通過Controller從Authentication獲取用戶名

Springboot get username from Authentication via Controller(Springboot通過Controller從Authentication獲取用戶名)
本文介紹了Springboot通過Controller從Authentication獲取用戶名的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!

問題描述

問題:我想僅從 authenticate.getName()... 獲取/提取用戶名/電子郵件,如果可能,而不是使用解析字符串.

Problem: I would like to get/extract the username/email only from authenticate.getName()... if possible, not by using parsing the string.

authentication.getName() 或 principal.getName() 值:

[username]: org.springframework.security.core.userdetails.User@21463e7a: Username: butitoy@iyotbihagay.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities

在本例中,我只想獲取用戶名的值,即 butitoy@iyotbihagay.com

解決方案:

由于我只想獲取用戶名/電子郵件 (butitoy@iyotbihagay.com),并且它返回整個(gè)主要內(nèi)容/文本(上圖),因此我將我在主題中設(shè)置的值替換為主要值... 到電子郵件值.. 它現(xiàn)在可以工作了.

Since I only want to get the username/email (butitoy@iyotbihagay.com), and it is returning the whole principal content/text (above), I replaced the value I set in the subject from the pricipal value... to the email value.. and it works now.

@Override
protected void successfulAuthentication(HttpServletRequest req,
                                        HttpServletResponse res,
                                        FilterChain chain,
                                        Authentication auth) throws IOException, ServletException {
    String email = auth.getName();
    String principal = auth.getPrincipal().toString();
    Date expiration = new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME);
    String token = Jwts.builder()
            .setSubject(email) //from principal to email
            .setExpiration(expiration)
            .signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET.getBytes())
            .compact();
    AuthenticatedUser loginUser = new AuthenticatedUser(email);
    loginUser.setToken(token);
    String jsonUser = Util.objectToJsonResponseAsString(loginUser, "user");
    res.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token);
    res.setContentType("application/json");
    res.setCharacterEncoding(ConstantUtil.DEFAULT_ENCODING);
    res.getWriter().write(jsonUser);
}

我現(xiàn)在可以使用不同的方式獲取用戶名/電子郵件值,例如你們建議的方式……甚至是我目前使用的方式.我現(xiàn)在不需要任何特殊的解析來從 Authentication 對(duì)象中獲取電子郵件值.

I can now get the username/email value using different ways like the one you guys are suggesting... even the one I am currently using. I do not need any special parsing now just to get the email value from the Authentication object.

在我之前使用 Spring 的非 RESTful 應(yīng)用程序中...我可以使用控制器方法參數(shù)中注入的 Authentication 類輕松獲取用戶名.

On my previous non RESTful application using Spring... I can easily get the username using Authentication class injected in the controller method parameter.

控制器:

...  
public Ticket getBySwertresNo(Authentication authentication, @PathVariable String swertresNo) {  
    logger.debug("Inside getBySwertresNo: " + swertresNo);  
    System.out.println("
[username]: " + authentication.getName() + "
");  
    return m_sugalService.getSwertresInfoBySwertresNo(swertresNo);  
}  
...  

控制臺(tái):

[username]: butitoy@iyotbihagay.com

現(xiàn)在,在我當(dāng)前的項(xiàng)目中……我使用了 RESTful 方法,在成功驗(yàn)證后,我返回了一個(gè)令牌,該令牌將在請(qǐng)求標(biāo)頭中使用/注入.我可以使用令牌登錄...但是當(dāng)我獲得 authentication.getName() 的值時(shí)...返回的不僅僅是電子郵件地址,它還包含一些其他信息.

Now, on my current project... I used a RESTful approach and after successful authentication, I am returning a token which will be used/injected in the request header. I can login using the token... but when I get the value of authentication.getName()... the return is not just the email address but it contains some other information.

控制臺(tái)(REST + JWT):

[username]: org.springframework.security.core.userdetails.User@21463e7a: Username: butitoy@iyotbihagay.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities

我只想獲取用戶名值butitoy@iyotbihagay.com".

I would like to get only the username value which is "butitoy@iyotbihagay.com".

JWT 身份驗(yàn)證過濾器:

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req,
                                                HttpServletResponse res) throws AuthenticationException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        return authentication;
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest req,
                                            HttpServletResponse res,
                                            FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {
        String email = auth.getName();
        String principal = auth.getPrincipal().toString();
        Date expiration = new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME);
        String token = Jwts.builder()
                .setSubject(principal)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET.getBytes())
                .compact();
        AuthenticatedUser loginUser = new AuthenticatedUser(email);
        loginUser.setToken(token);
        String jsonUser = Util.objectToJsonResponseAsString(loginUser, "user");
        res.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token);
        res.setContentType("application/json");
        res.setCharacterEncoding(ConstantUtil.DEFAULT_ENCODING);
        res.getWriter().write(jsonUser);
    }

}

JWT 授權(quán)過濾器:

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    public JWTAuthorizationFilter(AuthenticationManager authManager) {
        super(authManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest req,
                                    HttpServletResponse res,
                                    FilterChain chain) throws IOException, ServletException {
        String header = req.getHeader(SecurityConstants.HEADER_STRING);

        if (header == null || !header.startsWith(SecurityConstants.TOKEN_PREFIX)) {
            chain.doFilter(req, res);
            return;
        }

        UsernamePasswordAuthenticationToken authentication = getAuthentication(req);

SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(req, res);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(SecurityConstants.HEADER_STRING);
        if (token != null) {
            // parse the token.
            String user = Jwts.parser()
                    .setSigningKey(SecurityConstants.SECRET.getBytes())
                    .parseClaimsJws(token.replace(SecurityConstants.TOKEN_PREFIX, ""))
                    .getBody()
                    .getSubject();

            if (user != null) {
                return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
            }
            return null;
        }
        return null;
    }

}

推薦答案

我認(rèn)為你可以在類型的注入控制器參數(shù)中使用 authentication.getNameprincipal.getName身份驗(yàn)證Principal:

I think you can use authentication.getName and principal.getName in the injected controller argument of type Authentication and Principal:

@Controller
@RequestMapping("/info")
public class GetNameController {

    @RequestMapping(value = "/name", method = RequestMethod.GET)
    public String getName(Authentication authentication, Principal principal) {
        System.out.println(authentication.getName());
        System.out.println("-----------------");
        System.out.println(principal.getName());
        return "";
    }
}

可以生產(chǎn)

admin
-----------------
admin

這篇關(guān)于Springboot通過Controller從Authentication獲取用戶名的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

How to wrap text around components in a JTextPane?(如何在 JTextPane 中的組件周圍環(huán)繞文本?)
MyBatis, how to get the auto generated key of an insert? [MySql](MyBatis,如何獲取插入的自動(dòng)生成密鑰?[MySql])
Inserting to Oracle Nested Table in Java(在 Java 中插入 Oracle 嵌套表)
Java: How to insert CLOB into oracle database(Java:如何將 CLOB 插入 oracle 數(shù)據(jù)庫(kù))
Why does Spring-data-jdbc not save my Car object?(為什么 Spring-data-jdbc 不保存我的 Car 對(duì)象?)
Use threading to process file chunk by chunk(使用線程逐塊處理文件)
主站蜘蛛池模板: 99久久亚洲 | 天堂综合 | 一级片免费视频 | 欧美成视频 | 乱一性一乱一交一视频a∨ 色爱av | 日本中文在线视频 | 99精品国自产在线 | 在线免费看91 | 二区国产 | 中文字幕一区在线观看视频 | 激情一区二区三区 | 日本黄色大片免费 | 中文字幕日韩欧美 | 日韩影音 | 久久久久久久久久久蜜桃 | 日韩成人在线视频 | 欧美成人精品在线 | 亚洲国产精品一区 | 在线播放中文字幕 | 久久久久成人精品免费播放动漫 | 国产一区二区中文字幕 | 久久网一区二区 | 亚洲网站观看 | 拍拍无遮挡人做人爱视频免费观看 | 成人18亚洲xxoo | 日韩精品1区2区3区 国产精品国产成人国产三级 | 奇米在线| 日本三级做a全过程在线观看 | 神马久久春色视频 | 日韩视频精品在线 | 亚洲国产精品自拍 | 久久综合久 | 国产精品一区在线 | 91麻豆久久久 | 国产一区二区在线免费观看 | 综合色播 | 亚洲一区精品在线 | 日韩中文字幕一区二区 | 欧美三级在线 | 久久久久久免费毛片精品 | 成人在线视频免费观看 |