页面获取Spring Security登录用户

在session中取得spring security的登录用户名如下:

${session.SPRING_SECURITY_CONTEXT.authentication.principal.username}  

spring security 把SPRING_SECURITY_CONTEXT 放入了session 没有直接把username 放进去。下面一段代码主要描述的是session中的存的变量,

存跳转时候的URLsession {SPRING_SECURITY_SAVED_REQUEST_KEY=SavedRequest[http://localhost:8080/AVerPortal/resourceAction/resourceIndex.action]}
存的是登录成功时候session中存的信息:

    session {SPRING_SECURITY_CONTEXT=org.springframework.security.context.SecurityContextImpl@87b16984: Authentication: org.springframework.security.providers.cas.CasAuthenticationToken@87b16984: Principal: com.avi.casExtends.UserInfo@ff631d80: Username: test; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.ui.WebAuthenticationDetails@12afc: RemoteIpAddress: 127.0.0.1; SessionId: AE56E8925195DFF4C50ABD384574CCEA; Granted Authorities: ROLE_ADMIN Assertion: org.jasig.cas.client.validation.AssertionImpl@661a11 Credentials (Service/Proxy Ticket): ST-3-1lX3acgZ6HNgmhvjXuxB-cas, userId=2, userName=test}

在后台获取

UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()  
    .getAuthentication()  
    .getPrincipal();  
  
userDetails.getUsername()  
package com.easykotlin.reakt.controller

import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

/**
 * Created by Kor on 2017-12-24 14:04:07.
 */
@RestController
@RequestMapping("/user")
class UserController {

    @GetMapping(value = ["/currentUser.json"])
    fun currentUser(): UserDto {
        val UserDto = UserDto()
        try {
            UserDto.success = true
            val loginUser = UserController.UserDto.LoginUser()
            val UserDetails = SecurityContextHolder
                .getContext()
                .authentication
                .principal
                    as UserDetails
            loginUser.username = UserDetails.username
            UserDto.loginUser = loginUser
        } catch (e: Exception) {
            UserDto.success = false
            UserDto.loginUser = UserController.UserDto.LoginUser()
            e.printStackTrace()
        }
        return UserDto;
    }

    class UserDto {
        var success = false
        lateinit var loginUser: LoginUser

        class LoginUser {
            var username = "NULL"
        }
    }

}

你可能感兴趣的:(页面获取Spring Security登录用户)