Here are the examples of the java api org.springframework.security.web.RedirectStrategy taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
59 Examples
19
Source : Auth2LoginAuthenticationFilter.java
with MIT License
from ZeroOrInfinity
with MIT License
from ZeroOrInfinity
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
19
Source : AuthenticationUtil.java
with MIT License
from ZeroOrInfinity
with MIT License
from ZeroOrInfinity
private static void redirectProcessing(HttpServletRequest request, HttpServletResponse response, LoginProcessType loginProcessType, RedirectStrategy redirectStrategy, ErrorCodeEnum errorCodeEnum, String redirectUrl) throws IOException {
if (LoginProcessType.JSON.equals(loginProcessType)) {
int status = HttpStatus.UNAUTHORIZED.value();
responseWithJson(response, status, toJsonString(ResponseResult.fail(errorCodeEnum, redirectUrl)));
return;
}
redirectStrategy.sendRedirect(request, response, redirectUrl);
}
19
Source : AuthenticationUtil.java
with MIT License
from ZeroOrInfinity
with MIT License
from ZeroOrInfinity
/**
* 根据 LoginProcessType 进行 logout 转发处理
* @param request request
* @param response response
* @param logoutSuccessUrl logoutSuccessUrl
* @param loginProcessType {@link LoginProcessType}
* @param redirectStrategy redirectStrategy
* @param errorCodeEnum errorCodeEnum
* @throws IOException IOException
*/
public static void redirectProcessingLogoutByLoginProcessType(HttpServletRequest request, HttpServletResponse response, String logoutSuccessUrl, LoginProcessType loginProcessType, RedirectStrategy redirectStrategy, ErrorCodeEnum errorCodeEnum) throws IOException {
redirectProcessing(request, response, loginProcessType, redirectStrategy, errorCodeEnum, logoutSuccessUrl);
}
19
Source : AuthenticationUtil.java
with MIT License
from ZeroOrInfinity
with MIT License
from ZeroOrInfinity
/**
* 根据 LoginProcessType 进行转发处理
* @param request request
* @param response response
* @param loginProcessType {@link LoginProcessType}
* @param redirectStrategy redirectStrategy
* @param errorCodeEnum errorCodeEnum
* @param redirectUrl redirectUrl
* @throws IOException IOException
*/
public static void redirectProcessingByLoginProcessType(HttpServletRequest request, HttpServletResponse response, LoginProcessType loginProcessType, RedirectStrategy redirectStrategy, ErrorCodeEnum errorCodeEnum, String redirectUrl) throws IOException {
String referer = ofNullable(request.getHeader(SecurityConstants.HEADER_REFERER)).orElse(redirectUrl);
redirectProcessing(request, response, loginProcessType, redirectStrategy, errorCodeEnum, referer);
}
18
Source : OauthLogoutSuccessHandler.java
with Apache License 2.0
from zlt2000
with Apache License 2.0
from zlt2000
/**
* @author zlt
* @date 2020/3/10
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
public clreplaced OauthLogoutSuccessHandler implements LogoutSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String redirectUri = request.getParameter("redirect_uri");
if (StrUtil.isNotEmpty(redirectUri)) {
// 重定向指定的地址
redirectStrategy.sendRedirect(request, response, redirectUri);
} else {
response.setStatus(HttpStatus.OK.value());
response.setCharacterEncoding("UTF-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
PrintWriter writer = response.getWriter();
String jsonStr = JsonUtil.toJSONString(Result.succeed("登出成功"));
writer.write(jsonStr);
writer.flush();
}
}
}
18
Source : MyAuthenticationSucessHandler.java
with MIT License
from wuyouzhuguli
with MIT License
from wuyouzhuguli
@Component
public clreplaced MyAuthenticationSucessHandler implements AuthenticationSuccessHandler {
// private RequestCache requestCache = new HttpSessionRequestCache();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
//
// @Autowired
// private ObjectMapper mapper;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
// response.setContentType("application/json;charset=utf-8");
// response.getWriter().write(mapper.writeValuereplacedtring(authentication));
// SavedRequest savedRequest = requestCache.getRequest(request, response);
// System.out.println(savedRequest.getRedirectUrl());
// redirectStrategy.sendRedirect(request, response, savedRequest.getRedirectUrl());
redirectStrategy.sendRedirect(request, response, "/index");
}
}
18
Source : RedirectAuthenticationFailureHandler.java
with MIT License
from pzinsta
with MIT License
from pzinsta
public clreplaced RedirectAuthenticationFailureHandler implements AuthenticationFailureHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private String defaultReturnUrl = "/";
private String queryParam = "loginError";
private static final Logger LOGGER = LogManager.getLogger(RedirectAuthenticationFailureHandler.clreplaced);
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(request.getServletPath());
uriComponentsBuilder.queryParam(queryParam);
uriComponentsBuilder.queryParam(StringUtils.defaultIfEmpty(request.getQueryString(), StringUtils.EMPTY));
UriComponents uriComponents = uriComponentsBuilder.build();
String returnUrlWithQueryParameter = uriComponents.toUriString();
LOGGER.debug(returnUrlWithQueryParameter);
redirectStrategy.sendRedirect(request, response, returnUrlWithQueryParameter);
}
public RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
public String getDefaultReturnUrl() {
return defaultReturnUrl;
}
public void setDefaultReturnUrl(String defaultReturnUrl) {
this.defaultReturnUrl = defaultReturnUrl;
}
public String getQueryParam() {
return queryParam;
}
public void setQueryParam(String queryParam) {
this.queryParam = queryParam;
}
}
18
Source : SecurityExpiredSessionHandler.java
with MIT License
from PearAdmin
with MIT License
from PearAdmin
/**
* Describe: 自定义 Security 同账号多端登录挤下线 跳转地址
* Author: John Ming
* CreateTime: 2019/10/23
*/
@Component
public clreplaced SecurityExpiredSessionHandler implements SessionInformationExpiredStrategy {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
redirectStrategy.sendRedirect(event.getRequest(), event.getResponse(), "/login?kickout=1");
}
}
18
Source : CustomSuccessHandler.java
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
@Component
public clreplaced CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = targetUrl(authentication);
if (response.isCommitted()) {
System.out.println("Can't redirect");
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String targetUrl(Authentication authentication) {
String url = "";
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
List<String> roles = new ArrayList<String>();
for (GrantedAuthority a : authorities) {
roles.add(a.getAuthority());
}
System.out.println(roles);
if (isUserRole(roles)) {
url = "/deptform.html";
} else if (isAdminRole(roles)) {
url = "/deptform.html";
} else if (isHrAdminRole(roles)) {
url = "/deptform.html";
} else {
url = "/deptform.html";
}
return url;
}
private boolean isUserRole(List<String> roles) {
if (roles.contains("ROLE_USER")) {
return true;
}
return false;
}
private boolean isAdminRole(List<String> roles) {
if (roles.contains("ROLE_ADMIN")) {
return true;
}
return false;
}
private boolean isHrAdminRole(List<String> roles) {
if (roles.contains("ROLE_HR")) {
return true;
}
return false;
}
}
18
Source : CustomLogoutHandler.java
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
@Component
public clreplaced CustomLogoutHandler extends SimpleUrlLogoutSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
String targetUrl = targetUrl(authentication);
if (response.isCommitted()) {
System.out.println("Can't redirect");
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String targetUrl(Authentication authentication) {
UserDetails p = (UserDetails) authentication.getPrincipal();
String username = p.getUsername();
String preplacedword = p.getPreplacedword();
String url = "";
Collection<? extends GrantedAuthority> authorities = p.getAuthorities();
List<String> roles = new ArrayList<String>();
for (GrantedAuthority a : authorities) {
roles.add(a.getAuthority());
}
System.out.println("logout handler" + roles);
if (isUser(roles)) {
url = "/after_logout.html?message=" + "Thank your, " + username + " with preplacedword " + preplacedword + " and role(s): " + roles;
} else if (isAdmin(roles)) {
url = "/after_logout.html?message=" + "Thank your, " + username + " with preplacedword " + preplacedword + " and role(s): " + roles;
} else if (isHrAdmin(roles)) {
url = "/after_logout.html?message=" + "Thank your, " + username + " with preplacedword " + preplacedword + " and role(s): " + roles;
} else {
url = "/after_logout.html?message=" + "Thank you, friend!";
}
return url;
}
private boolean isUser(List<String> roles) {
if (roles.contains("ROLE_USER")) {
return true;
}
return false;
}
private boolean isAdmin(List<String> roles) {
if (roles.contains("ROLE_ADMIN")) {
return true;
}
return false;
}
private boolean isHrAdmin(List<String> roles) {
if (roles.contains("ROLE_HR")) {
return true;
}
return false;
}
}
18
Source : CustomFailureHandler.java
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
@Component
public clreplaced CustomFailureHandler extends SimpleUrlAuthenticationFailureHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
System.out.println("failure");
String targetUrl = "";
if (exception instanceof BadCredentialsException) {
targetUrl = "/login.html?error=" + exception.getMessage();
} else {
targetUrl = "/login.html?error=" + true;
}
if (response.isCommitted()) {
System.out.println("Internal problem in redirection");
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
}
18
Source : CustomLogoutHandler.java
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
@Component
public clreplaced CustomLogoutHandler extends SimpleUrlLogoutSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
String targetUrl = targetUrl(authentication);
if (response.isCommitted()) {
System.out.println("Can't redirect");
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String targetUrl(Authentication authentication) {
Collection<? extends GrantedAuthority> authorities;
String username;
String preplacedword;
String url = "";
try {
UserDetails p = (UserDetails) authentication.getPrincipal();
username = p.getUsername();
preplacedword = p.getPreplacedword();
authorities = p.getAuthorities();
System.out.println(authentication.isAuthenticated());
List<String> roles = new ArrayList<String>();
for (GrantedAuthority a : authorities) {
roles.add(a.getAuthority());
}
System.out.println("logout handler" + roles);
if (isUser(roles)) {
url = "/after_logout.html?message=" + "Thank your, " + username + " with preplacedword " + preplacedword + " and role(s): " + roles;
} else if (isAdmin(roles)) {
url = "/after_logout.html?message=" + "Thank your, " + username + " with preplacedword " + preplacedword + " and role(s): " + roles;
} else if (isHrAdmin(roles)) {
url = "/after_logout.html?message=" + "Thank your, " + username + " with preplacedword " + preplacedword + " and role(s): " + roles;
} else {
url = "/after_logout.html?message=" + "Thank you, friend!";
}
} catch (Exception e) {
System.out.println(authentication.getPrincipal());
username = (String) authentication.getPrincipal();
authorities = authentication.getAuthorities();
System.out.println(authentication.isAuthenticated());
List<String> roles = new ArrayList<String>();
for (GrantedAuthority a : authorities) {
roles.add(a.getAuthority());
}
System.out.println("logout handler" + roles);
if (isUser(roles)) {
url = "/after_logout.html?message=" + "Thank your, User!";
} else if (isAdmin(roles)) {
url = "/after_logout.html?message=" + "Thank your, Admin!";
} else if (isHrAdmin(roles)) {
url = "/after_logout.html?message=" + "Thank your, HR Admin!";
} else {
url = "/after_logout.html?message=" + "Thank you, friend!";
}
}
return url;
}
private boolean isUser(List<String> roles) {
if (roles.contains("ROLE_USER")) {
return true;
}
return false;
}
private boolean isAdmin(List<String> roles) {
if (roles.contains("ROLE_ADMIN")) {
return true;
}
return false;
}
private boolean isHrAdmin(List<String> roles) {
if (roles.contains("ROLE_HR")) {
return true;
}
return false;
}
}
18
Source : OAuth2AuthenticationSuccessHandler.java
with Apache License 2.0
from oktadeveloper
with Apache License 2.0
from oktadeveloper
/**
* AuthenticationSuccessHandler that looks for a saved login origin and redirects to it if it exists.
*/
public clreplaced OAuth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final Logger log = LoggerFactory.getLogger(OAuth2AuthenticationSuccessHandler.clreplaced);
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
handle(request, response);
clearAuthenticationAttributes(request);
}
private void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
String targetUrl = determineTargetUrl(request);
if (response.isCommitted()) {
log.error("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
private String determineTargetUrl(HttpServletRequest request) {
Object savedReferrer = request.getSession().getAttribute(SAVED_LOGIN_ORIGIN_URI);
if (savedReferrer != null) {
String savedLoginOrigin = request.getSession().getAttribute(SAVED_LOGIN_ORIGIN_URI).toString();
log.info("Redirecting to saved login origin URI: {}", savedLoginOrigin);
request.getSession().removeAttribute(SAVED_LOGIN_ORIGIN_URI);
return savedLoginOrigin;
} else {
return "/";
}
}
private void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
}
18
Source : OAuth2AuthenticationSuccessHandler.java
with Apache License 2.0
from oktadeveloper
with Apache License 2.0
from oktadeveloper
/**
* AuthenticationSuccessHandler that looks for a saved login origin and redirects to it if it exists.
*/
public clreplaced OAuth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final Logger log = LoggerFactory.getLogger(OAuth2AuthenticationSuccessHandler.clreplaced);
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
handle(request, response);
clearAuthenticationAttributes(request);
}
private void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
String targetUrl = determineTargetUrl(request);
if (response.isCommitted()) {
log.error("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
private String determineTargetUrl(HttpServletRequest request) {
Object savedReferrer = request.getSession().getAttribute(SAVED_LOGIN_ORIGIN_URI);
if (savedReferrer != null) {
String savedLoginOrigin = request.getSession().getAttribute(SAVED_LOGIN_ORIGIN_URI).toString();
log.debug("Redirecting to saved login origin URI: {}", savedLoginOrigin);
request.getSession().removeAttribute(SAVED_LOGIN_ORIGIN_URI);
return savedLoginOrigin;
} else {
return "/";
}
}
private void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
}
18
Source : MySimpleUrlAuthenticationFailureHandler.java
with Apache License 2.0
from luotuo
with Apache License 2.0
from luotuo
public clreplaced MySimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler {
protected final Log logger = LogFactory.getLog(this.getClreplaced());
private String defaultFailureUrl;
private boolean forwardToDestination = false;
private boolean allowSessionCreation = true;
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
public MySimpleUrlAuthenticationFailureHandler() {
}
public MySimpleUrlAuthenticationFailureHandler(String defaultFailureUrl) {
this.setDefaultFailureUrl(defaultFailureUrl);
}
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
if (this.defaultFailureUrl == null) {
if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "X-Request-With, LUOTUO, Origin,Content-Type, luotuo");
response.setCharacterEncoding("UTF-8");
response.setStatus(202);
} else {
this.logger.debug("No failure URL set, sending 401 Unauthorized error");
System.out.println("onAuthenticationFailure======================================");
ObjectMapper mapper = new ObjectMapper();
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "X-Request-With, LUOTUO, Origin,Content-Type");
response.setContentType("text/plain;charset='utf-8'");
response.setCharacterEncoding("UTF-8");
response.setStatus(200);
// Our ajax request, redirect it to login web page
Response response1 = new Response();
response1.setSuccess(1);
response1.setMessage("success");
response1.setResult("登录失败,用户名或密码错误");
String responseStr = "";
PrintWriter out = response.getWriter();
try {
responseStr = mapper.writeValuereplacedtring(response1);
out.append(responseStr);
} catch (IOException ioe) {
// FIXME: Add log here!
out.append(ioe.toString());
}
out.close();
System.out.println("Return our response!");
}
}
}
protected final void saveException(HttpServletRequest request, AuthenticationException exception) {
if (this.forwardToDestination) {
request.setAttribute("SPRING_SECURITY_LAST_EXCEPTION", exception);
} else {
HttpSession session = request.getSession(false);
if (session != null || this.allowSessionCreation) {
request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", exception);
}
}
}
public void setDefaultFailureUrl(String defaultFailureUrl) {
replacedert.isTrue(UrlUtils.isValidRedirectUrl(defaultFailureUrl), "'" + defaultFailureUrl + "' is not a valid redirect URL");
this.defaultFailureUrl = defaultFailureUrl;
}
protected boolean isUseForward() {
return this.forwardToDestination;
}
public void setUseForward(boolean forwardToDestination) {
this.forwardToDestination = forwardToDestination;
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return this.redirectStrategy;
}
protected boolean isAllowSessionCreation() {
return this.allowSessionCreation;
}
public void setAllowSessionCreation(boolean allowSessionCreation) {
this.allowSessionCreation = allowSessionCreation;
}
}
18
Source : CustomExpiredSessionStrategy.java
with Apache License 2.0
from jitwxs
with Apache License 2.0
from jitwxs
public clreplaced CustomExpiredSessionStrategy implements SessionInformationExpiredStrategy {
private ObjectMapper objectMapper = new ObjectMapper();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
/**
* 根据需要返回 Url 或者 Json
* @author jitwxs
* @since 2018/11/29 18:46
*/
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
Map<String, Object> map = new HashMap<>(16);
map.put("code", 0);
map.put("msg", "已经另一台机器登录,您被迫下线。" + event.getSessionInformation().getLastRequest());
// Map -> Json
String json = objectMapper.writeValuereplacedtring(map);
event.getResponse().setContentType("application/json;charset=UTF-8");
event.getResponse().getWriter().write(json);
// 如果是跳转html页面,url代表跳转的地址
// redirectStrategy.sendRedirect(event.getRequest(), event.getResponse(), "url");
}
}
18
Source : OauthLogoutSuccessHandler.java
with Apache License 2.0
from jbuider1993
with Apache License 2.0
from jbuider1993
/**
* @author zlt
* @date 2020/3/10
* <p>
* Blog: https://blog.csdn.net/zlt2000
* Github: https://github.com/zlt2000
*/
@Slf4j
public clreplaced OauthLogoutSuccessHandler implements LogoutSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String redirectUri = request.getParameter("redirect_uri");
if (StrUtil.isNotEmpty(redirectUri)) {
// 重定向指定的地址
redirectStrategy.sendRedirect(request, response, redirectUri);
} else {
response.setStatus(HttpStatus.OK.value());
response.setCharacterEncoding("UTF-8");
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
PrintWriter writer = response.getWriter();
String jsonStr = JSON.toJSONString(Result.succeed("登出成功"));
writer.write(jsonStr);
writer.flush();
}
}
}
18
Source : FebsInvalidSessionStrategy.java
with Apache License 2.0
from febsteam
with Apache License 2.0
from febsteam
/**
* 处理 session 失效
*/
public clreplaced FebsInvalidSessionStrategy implements InvalidSessionStrategy {
private FebsSecurityProperties securityProperties;
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException {
redirectStrategy.sendRedirect(request, response, securityProperties.getLogoutUrl());
}
public FebsSecurityProperties getSecurityProperties() {
return securityProperties;
}
public void setSecurityProperties(FebsSecurityProperties securityProperties) {
this.securityProperties = securityProperties;
}
}
18
Source : FebsAuthenticationAccessDeniedHandler.java
with Apache License 2.0
from febsteam
with Apache License 2.0
from febsteam
public clreplaced FebsAuthenticationAccessDeniedHandler implements AccessDeniedHandler {
private ObjectMapper mapper = new ObjectMapper();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
if (FebsUtil.isAjaxRequest(request)) {
response.setContentType(FebsConstant.JSON_UTF8);
response.getWriter().write(this.mapper.writeValuereplacedtring(ResponseBo.error("没有该权限!")));
} else {
redirectStrategy.sendRedirect(request, response, FebsConstant.FEBS_ACCESS_DENY_URL);
}
}
}
18
Source : CustomAuthenticationFailureHandler.java
with Mozilla Public License 2.0
from diging
with Mozilla Public License 2.0
from diging
public clreplaced CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
private final Logger logger = LoggerFactory.getLogger(getClreplaced());
private String defaultFailureUrl;
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
public CustomAuthenticationFailureHandler() {
}
public CustomAuthenticationFailureHandler(String defaultFailureUrl) {
setDefaultFailureUrl(defaultFailureUrl);
}
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
String errorKey;
if (exception.getClreplaced().equals(LockedException.clreplaced)) {
errorKey = "user_not_approved";
} else {
errorKey = "bad_credentials";
}
logger.debug("Redirecting to " + defaultFailureUrl + errorKey);
redirectStrategy.sendRedirect(request, response, defaultFailureUrl + errorKey);
}
/**
* The URL which will be used as the failure destination.
*
* @param defaultFailureUrl
* the failure URL, for example "/loginFailed.jsp".
*/
public void setDefaultFailureUrl(String defaultFailureUrl) {
replacedert.isTrue(UrlUtils.isValidRedirectUrl(defaultFailureUrl), () -> "'" + defaultFailureUrl + "' is not a valid redirect URL");
this.defaultFailureUrl = defaultFailureUrl;
}
}
18
Source : PlatformAuthenticationSuccessHandler.java
with GNU Lesser General Public License v2.1
from abixen
with GNU Lesser General Public License v2.1
from abixen
public clreplaced PlatformAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final Logger log = LoggerFactory.getLogger(PlatformAuthenticationSuccessHandler.clreplaced.getName());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
log.debug("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
/**
* Builds the target URL according to the logic defined in the main clreplaced Javadoc.
*/
protected String determineTargetUrl(Authentication authentication) {
log.debug("determineTargetUrl() - authentication: " + authentication);
boolean isUser = false;
boolean isAdmin = false;
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
log.debug("grantedAuthority: " + grantedAuthority);
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
isUser = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
isAdmin = true;
break;
}
}
if (isUser) {
return "/";
} else if (isAdmin) {
return "/control-panel";
} else {
throw new IllegalStateException();
}
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
17
Source : SsoLogoutSuccessHandler.java
with Apache License 2.0
from zlt2000
with Apache License 2.0
from zlt2000
/**
* 登出成功处理类
*
* @author zlt
* @date 2020/3/10
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
public clreplaced SsoLogoutSuccessHandler implements LogoutSuccessHandler {
@Value("${zlt.logout-uri:''}")
private String logoutUri;
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
OAuth2Authentication oauth2Authentication = (OAuth2Authentication) authentication;
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) oauth2Authentication.getDetails();
String accessToken = details.getTokenValue();
redirectStrategy.sendRedirect(request, response, logoutUri + accessToken);
}
}
17
Source : BrowserSecurityController.java
with MIT License
from wuyouzhuguli
with MIT License
from wuyouzhuguli
/**
* @author MrBird
*/
@RestController
public clreplaced BrowserSecurityController {
private RequestCache requestCache = new HttpSessionRequestCache();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
String targetUrl = savedRequest.getRedirectUrl();
if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
redirectStrategy.sendRedirect(request, response, "/login.html");
}
return "访问的资源需要身份认证!";
}
@GetMapping("/session/invalid")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String sessionInvalid() {
return "session已失效,请重新认证";
}
@GetMapping("/signout/success")
public String signout() {
return "退出成功,请重新登录";
}
@GetMapping("/auth/admin")
@PreAuthorize("hasAuthority('admin')")
public String authenticationTest() {
return "您拥有admin权限,可以查看";
}
}
17
Source : BrowserSecurityController.java
with MIT License
from wuyouzhuguli
with MIT License
from wuyouzhuguli
/**
* @author MrBird
*/
@RestController
public clreplaced BrowserSecurityController {
private RequestCache requestCache = new HttpSessionRequestCache();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
String targetUrl = savedRequest.getRedirectUrl();
if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
redirectStrategy.sendRedirect(request, response, "/login.html");
}
return "访问的资源需要身份认证!";
}
@GetMapping("/session/invalid")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String sessionInvalid() {
return "session已失效,请重新认证";
}
@GetMapping("/signout/success")
public String signout() {
return "退出成功,请重新登录";
}
}
17
Source : BrowserSecurityController.java
with MIT License
from wuyouzhuguli
with MIT License
from wuyouzhuguli
/**
* @author MrBird
*/
@RestController
public clreplaced BrowserSecurityController {
private RequestCache requestCache = new HttpSessionRequestCache();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
String targetUrl = savedRequest.getRedirectUrl();
if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
redirectStrategy.sendRedirect(request, response, "/login.html");
}
return "访问的资源需要身份认证!";
}
@GetMapping("/session/invalid")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String sessionInvalid() {
return "session已失效,请重新认证";
}
}
17
Source : BrowserSecurityController.java
with MIT License
from wuyouzhuguli
with MIT License
from wuyouzhuguli
/**
* @author MrBird
*/
@RestController
public clreplaced BrowserSecurityController {
private RequestCache requestCache = new HttpSessionRequestCache();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
String targetUrl = savedRequest.getRedirectUrl();
if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
redirectStrategy.sendRedirect(request, response, "/login.html");
}
return "访问的资源需要身份认证!";
}
}
17
Source : AppAuthPoint.java
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
public clreplaced AppAuthPoint extends LoginUrlAuthenticationEntryPoint {
@Autowired
private AuthenticationTrustResolver trustResolver;
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
public AppAuthPoint(final String loginFormUrl) {
super(loginFormUrl);
}
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null || trustResolver.isAnonymous(auth)) {
redirectStrategy.sendRedirect(request, response, "/deptanon.html");
} else {
String redirectUrl = buildRedirectUrlToLoginPage(request, response, authException);
redirectStrategy.sendRedirect(request, response, redirectUrl);
}
}
}
17
Source : DefaultAccessDeniedHandler.java
with Apache License 2.0
from miyabayt
with Apache License 2.0
from miyabayt
public clreplaced DefaultAccessDeniedHandler implements AccessDeniedHandler {
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Autowired
AuthenticationEntryPoint authenticationEntryPoint;
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
if (response.isCommitted()) {
return;
}
if (accessDeniedException instanceof MissingCsrfTokenException || accessDeniedException instanceof InvalidCsrfTokenException) {
authenticationEntryPoint.commence(request, response, null);
} else {
redirectStrategy.sendRedirect(request, response, FORBIDDEN_URL);
}
}
}
17
Source : GithubLoginSuccessHandler.java
with MIT License
from microsoft
with MIT License
from microsoft
@NoArgsConstructor
public clreplaced GithubLoginSuccessHandler implements AuthenticationSuccessHandler {
private static final String TELEMETRY_EVENT_GITHUB_LOGIN = "playground-github-login";
private final TelemetryProxy telemetryProxy = new TelemetryProxy();
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private void triggerGithubLoginSuccessEvent(@NonNull String username) {
Map<String, String> properties = new HashMap<>();
properties.put("uniqueId", sha256Hex(username));
this.telemetryProxy.trackEvent(TELEMETRY_EVENT_GITHUB_LOGIN, properties);
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException {
String targetUrl = "/";
OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) auth;
String username = oauthToken.getPrincipal().getAttributes().get("login").toString();
triggerGithubLoginSuccessEvent(username);
redirectStrategy.sendRedirect(request, response, targetUrl);
}
}
17
Source : MyAuthenticationSuccessHandler.java
with Apache License 2.0
from luotuo
with Apache License 2.0
from luotuo
public clreplaced MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
protected final Log logger = LogFactory.getLog(this.getClreplaced());
private RequestCache requestCache = new HttpSessionRequestCache();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
public MyAuthenticationSuccessHandler() {
}
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
SavedRequest savedRequest = this.requestCache.getRequest(request, response);
if (savedRequest == null) {
// super.onAuthenticationSuccess(request, response, authentication);
handle(request, response, authentication);
super.clearAuthenticationAttributes(request);
} else {
String targetUrlParameter = this.getTargetUrlParameter();
if (!this.isAlwaysUseDefaultTargetUrl() && (targetUrlParameter == null || !StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
this.clearAuthenticationAttributes(request);
String targetUrl = savedRequest.getRedirectUrl();
this.logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
// this.getRedirectStrategy().sendRedirect(request, response, targetUrl);
} else {
this.requestCache.removeRequest(request, response);
// super.onAuthenticationSuccess(request, response, authentication);
handle(request, response, authentication);
super.clearAuthenticationAttributes(request);
}
}
}
public void setRequestCache(RequestCache requestCache) {
this.requestCache = requestCache;
}
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
String targetUrl = this.determineTargetUrl(request, response);
if (response.isCommitted()) {
this.logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
} else {
ObjectMapper mapper = new ObjectMapper();
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "X-Request-With, JWCQ, Origin,Content-Type");
response.setContentType("text/plain;charset='utf-8'");
response.setCharacterEncoding("UTF-8");
response.setStatus(200);
// Our ajax request, redirect it to login web page
Response response1 = new Response();
response1.setSuccess(1);
response1.setMessage("success");
response1.setResult("登录成功");
String responseStr = "";
PrintWriter out = response.getWriter();
try {
responseStr = mapper.writeValuereplacedtring(response1);
out.append(responseStr);
} catch (IOException ioe) {
// FIXME: Add log here!
out.append(ioe.toString());
}
out.close();
}
}
}
17
Source : SsoLogoutSuccessHandler.java
with Apache License 2.0
from jbuider1993
with Apache License 2.0
from jbuider1993
/**
* 登出成功处理类
*
* @author zlt
* @date 2020/3/10
* <p>
* Blog: https://blog.csdn.net/zlt2000
* Github: https://github.com/zlt2000
*/
@Component
public clreplaced SsoLogoutSuccessHandler implements LogoutSuccessHandler {
@Value("${zlt.logout-uri:''}")
private String logoutUri;
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
OAuth2Authentication oauth2Authentication = (OAuth2Authentication) authentication;
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) oauth2Authentication.getDetails();
String accessToken = details.getTokenValue();
redirectStrategy.sendRedirect(request, response, logoutUri + accessToken);
}
}
17
Source : LoginSuccessHandler.java
with Apache License 2.0
from huifer
with Apache License 2.0
from huifer
/**
* 描述:
*
* @author huifer
* @date 2019-03-24
*/
public clreplaced LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Autowired
private SysResourceRepository resourceRepository;
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
System.out.println(authentication);
System.out.println(authentication.getPrincipal());
// 获得授权后可得到用户信息
SysUser user = (SysUser) authentication.getPrincipal();
// 输出登录提示信息
System.out.println("用户名: " + user.getUsername());
System.out.println("用户密码: " + user.getPreplacedword());
System.out.println("角色列表:" + authentication.getAuthorities());
System.out.println("IP信息 :" + authentication.getDetails());
System.out.println("是否被授权 :" + authentication.isAuthenticated());
// 登录成功后跳转到默认对应的页面
String targetUrl = "/home";
for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
String roleName = grantedAuthority.getAuthority();
switch(roleName) {
case "ADMIN":
targetUrl = "/admin";
break;
case "VIP":
targetUrl = "/vip";
break;
}
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
}
17
Source : AbstractSessionStrategy.java
with Apache License 2.0
from hellosmile01
with Apache License 2.0
from hellosmile01
/**
* @author zhailiang
*/
public clreplaced AbstractSessionStrategy {
private final Logger logger = LoggerFactory.getLogger(getClreplaced());
/**
* 跳转的url
*/
private String destinationUrl;
/**
* 重定向策略
*/
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
/**
* 跳转前是否创建新的session
*/
private boolean createNewSession = true;
private ObjectMapper objectMapper = new ObjectMapper();
/**
* @param invalidSessionUrl
* @param invalidSessionHtmlUrl
*/
public AbstractSessionStrategy(String invalidSessionUrl) {
replacedert.isTrue(UrlUtils.isValidRedirectUrl(invalidSessionUrl), "url must start with '/' or with 'http(s)'");
this.destinationUrl = invalidSessionUrl;
}
/*
* (non-Javadoc)
*
* @see org.springframework.security.web.session.InvalidSessionStrategy#
* onInvalidSessionDetected(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
protected void onSessionInvalid(HttpServletRequest request, HttpServletResponse response) throws IOException {
if (createNewSession) {
request.getSession();
}
String sourceUrl = request.getRequestURI();
String targetUrl;
if (StringUtils.endsWithIgnoreCase(sourceUrl, ".html")) {
targetUrl = destinationUrl + ".html";
logger.info("session失效,跳转到" + targetUrl);
redirectStrategy.sendRedirect(request, response, targetUrl);
} else {
String message = "session已失效";
if (isConcurrency()) {
message = message + ",有可能是并发登录导致的";
}
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValuereplacedtring(new SimpleResponse(message)));
}
}
/**
* session失效是否是并发导致的
* @return
*/
protected boolean isConcurrency() {
return false;
}
/**
* Determines whether a new session should be created before redirecting (to
* avoid possible looping issues where the same session ID is sent with the
* redirected request). Alternatively, ensure that the configured URL does
* not preplaced through the {@code SessionManagementFilter}.
*
* @param createNewSession
* defaults to {@code true}.
*/
public void setCreateNewSession(boolean createNewSession) {
this.createNewSession = createNewSession;
}
}
17
Source : KeycloakLogoutHandler.java
with Apache License 2.0
from camunda
with Apache License 2.0
from camunda
/**
* Keycloak Logout Handler.
*/
@Service
public clreplaced KeycloakLogoutHandler implements LogoutSuccessHandler {
/**
* This clreplaced' logger.
*/
private static final Logger LOG = LoggerFactory.getLogger(KeycloakLogoutHandler.clreplaced);
/**
* Redirect strategy.
*/
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
/**
* Keycloak's logout URI.
*/
private String oauth2UserLogoutUri;
/**
* Default constructor.
* @param oauth2UserAuthorizationUri configured keycloak authorization URI
*/
public KeycloakLogoutHandler(@Value("${spring.security.oauth2.client.provider.keycloak.authorization-uri:}") String oauth2UserAuthorizationUri) {
if (!StringUtils.isEmpty(oauth2UserAuthorizationUri)) {
// in order to get the valid logout uri: simply replace "/auth" at the end of the user authorization uri with "/logout"
this.oauth2UserLogoutUri = oauth2UserAuthorizationUri.replace("openid-connect/auth", "openid-connect/logout");
}
}
/**
* {@inheritDoc}
*/
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
if (!StringUtils.isEmpty(oauth2UserLogoutUri)) {
// Calculate redirect URI for Keycloak, something like http://<host:port>/camunda
String requestUrl = request.getRequestURL().toString();
String redirectUri = requestUrl.substring(0, requestUrl.indexOf("/app"));
// Complete logout URL
String logoutUrl = oauth2UserLogoutUri + "?redirect_uri=" + redirectUri;
// Do logout by redirecting to Keycloak logout
LOG.debug("Redirecting to logout URL {}", logoutUrl);
redirectStrategy.sendRedirect(request, response, logoutUrl);
}
}
}
16
Source : Auth2LoginAuthenticationFilter.java
with MIT License
from ZeroOrInfinity
with MIT License
from ZeroOrInfinity
/**
* An implementation of an {@link AbstractAuthenticationProcessingFilter} for OAuth 2.0
* Login.
*
* @author Joe Grandja
* @author YongWu zheng
* @since 5.0
* @see AbstractAuthenticationProcessingFilter
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section
* 4.1 Authorization Code Grant</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.2">Section 4.1.2 Authorization
* Response</a>
*/
@SuppressWarnings("JavaDoc")
public clreplaced Auth2LoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public static final String TEMPORARY_USER_CACHE_KEY_PREFIX = "TEMPORARY_USER_REDIS_CACHE_KEY:";
public static final String TEMPORARY_USERNAME_PARAM_NAME = "temporary_username";
private static final String AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE = "authorization_request_not_found";
private final Auth2DefaultRequestResolver authorizationRequestResolver;
private final RedisConnectionFactory redisConnectionFactory;
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
/**
* 第三方授权登录后如未注册用户不支持自动注册功能, 则跳转到此 url 进行注册逻辑, 此 url 必须开发者自己实现
*/
private final String signUpUrl;
/**
* Constructs an {@code Auth2LoginAuthenticationFilter} using the provided
* parameters.
* @param filterProcessesUrl the {@code URI} where this {@code Filter} will process
* the authentication requests, not null
* @param signUpUrl 第三方授权登录后如未注册用户不支持自动注册功能, 则跳转到此 url 进行注册逻辑, 此 url 必须开发者自己实现;
* @param authenticationDetailsSource {@link AuthenticationDetailsSource}
* @param redisConnectionFactory redis connection factory
* @since 5.1
*/
public Auth2LoginAuthenticationFilter(@NonNull String filterProcessesUrl, @NonNull String signUpUrl, @Nullable AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource, @Autowired(required = false) @Nullable RedisConnectionFactory redisConnectionFactory) {
super(filterProcessesUrl + "/*");
this.authorizationRequestResolver = new Auth2DefaultRequestResolver(filterProcessesUrl);
this.signUpUrl = signUpUrl;
this.redisConnectionFactory = redisConnectionFactory;
if (authenticationDetailsSource != null) {
setAuthenticationDetailsSource(authenticationDetailsSource);
}
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
// noinspection unchecked
MultiValueMap<String, String> params = Auth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap());
if (!Auth2AuthorizationResponseUtils.isAuthorizationResponse(params)) {
OAuth2Error oauth2Error = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
String registrationId = this.authorizationRequestResolver.resolveRegistrationId(request);
Auth2DefaultRequest auth2DefaultRequest = null;
if (StringUtils.hasText(registrationId)) {
auth2DefaultRequest = Auth2RequestHolder.getAuth2DefaultRequest(registrationId);
}
if (auth2DefaultRequest == null) {
OAuth2Error oauth2Error = new OAuth2Error(AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE, "Client Registration not found with Id: " + registrationId, null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
Auth2LoginAuthenticationToken authenticationRequest = new Auth2LoginAuthenticationToken(auth2DefaultRequest, request);
// Allow subclreplacedes to set the "details" property
setDetails(request, authenticationRequest);
// 通过 AuthenticationManager 转到相应的 Provider 对 Auth2LoginAuthenticationToken 进行认证
return this.getAuthenticationManager().authenticate(authenticationRequest);
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Authentication success. Updating SecurityContextHolder to contain: " + authResult);
}
SecurityContextHolder.getContext().setAuthentication(authResult);
// Fire event
if (this.eventPublisher != null) {
eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClreplaced()));
}
// 自定义注册逻辑
final Object principal = authResult.getPrincipal();
if (principal instanceof TemporaryUser && StringUtils.hasText(this.signUpUrl)) {
TemporaryUser temporaryUser = (TemporaryUser) principal;
String username = temporaryUser.getUsername();
String key = TEMPORARY_USER_CACHE_KEY_PREFIX + username;
if (nonNull(redisConnectionFactory)) {
// 存入 redis
try (RedisConnection connection = redisConnectionFactory.getConnection()) {
connection.set(key.getBytes(StandardCharsets.UTF_8), JsonUtil.toJsonString(temporaryUser).getBytes(StandardCharsets.UTF_8), Expiration.from(86400L, TimeUnit.SECONDS), RedisStringCommands.SetOption.UPSERT);
}
} else {
// 存入 session
request.getSession().setAttribute(key, temporaryUser);
}
this.redirectStrategy.sendRedirect(request, response, this.signUpUrl + "?" + TEMPORARY_USERNAME_PARAM_NAME + "=" + username);
return;
} else {
getRememberMeServices().loginSuccess(request, response, authResult);
}
getSuccessHandler().onAuthenticationSuccess(request, response, authResult);
}
/**
* Provided so that subclreplacedes may configure what is put into the auth
* request's details property.
*
* @param request that an auth request is being created for
* @param authRequest the auth request object that should have its details
* set
*/
protected void setDetails(HttpServletRequest request, Auth2LoginAuthenticationToken authRequest) {
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
}
16
Source : DefaultRedirectInvalidSessionStrategy.java
with MIT License
from ZeroOrInfinity
with MIT License
from ZeroOrInfinity
/**
* Performs a redirect to a fixed URL when an invalid requested session is detected by the
* {@code SessionManagementFilter}.<br><br>
* 继承此类并注入 IOC 容器会替换此类
* @author Luke Taylor
* @author YongWu zheng
*/
@Slf4j
public final clreplaced DefaultRedirectInvalidSessionStrategy implements InvalidSessionStrategy {
private final String destinationUrl;
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private final AntPathMatcher matcher;
private final RequestCache requestCache;
public DefaultRedirectInvalidSessionStrategy(String invalidSessionUrl) {
replacedert.isTrue(UrlUtils.isValidRedirectUrl(invalidSessionUrl), "url must start with '/' or with 'http(s)'");
this.destinationUrl = invalidSessionUrl;
this.matcher = new AntPathMatcher();
this.requestCache = new HttpSessionRequestCache();
}
@Override
public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException {
String redirectUrl = determineInvalidSessionRedirectUrl(request, response, destinationUrl, matcher, requestCache);
if (log.isDebugEnabled()) {
log.debug("Starting new session and redirecting to '{}'", redirectUrl);
}
redirectStrategy.sendRedirect(request, response, redirectUrl);
}
}
15
Source : ClientExpiredSessionStrategy.java
with MIT License
from ZeroOrInfinity
with MIT License
from ZeroOrInfinity
/**
* Performs a redirect to a fixed URL when an expired session is detected by the
* {@code ConcurrentSessionFilter}.
* @author YongWu zheng
* @version V1.0 Created by 2020/6/2 23:21
*/
@Slf4j
public clreplaced ClientExpiredSessionStrategy implements SessionInformationExpiredStrategy {
private final RedirectStrategy redirectStrategy;
private final LoginProcessType loginProcessType;
private final String loginPage;
private final RequestCache requestCache;
private final AntPathMatcher matcher;
public ClientExpiredSessionStrategy(ClientProperties clientProperties) {
this.loginProcessType = clientProperties.getLoginProcessType();
this.loginPage = clientProperties.getLoginPage();
this.matcher = new AntPathMatcher();
this.redirectStrategy = new DefaultRedirectStrategy();
this.requestCache = new HttpSessionRequestCache();
}
@SuppressWarnings("RedundantThrows")
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
HttpServletRequest request = event.getRequest();
HttpServletResponse response = event.getResponse();
HttpSession session = request.getSession(true);
try {
// 清除缓存
session.removeAttribute(SESSION_ENHANCE_CHECK_KEY);
String redirectUrl = determineInvalidSessionRedirectUrl(request, response, loginPage, matcher, requestCache);
if (log.isDebugEnabled()) {
log.debug("Session expired, starting new session and redirecting to '{}'", redirectUrl);
}
redirectProcessingByLoginProcessType(request, response, loginProcessType, redirectStrategy, ErrorCodeEnum.EXPIRED_SESSION, redirectUrl);
} catch (Exception e) {
log.error(String.format("SESSION过期处理失败: error=%s, ip=%s, sid=%s, uri=%s", e.getMessage(), IpUtil.getRealIp(request), session.getId(), request.getRequestURI()), e);
throw new ExpiredSessionDetectedException(ErrorCodeEnum.SERVER_ERROR, session.getId());
}
}
}
15
Source : OAuth2AuthorizationEndpointFilter.java
with Apache License 2.0
from spring-projects-experimental
with Apache License 2.0
from spring-projects-experimental
/**
* A {@code Filter} for the OAuth 2.0 Authorization Code Grant,
* which handles the processing of the OAuth 2.0 Authorization Request.
*
* @author Joe Grandja
* @author Paurav Munshi
* @author Daniel Garnier-Moiroux
* @since 0.0.1
* @see RegisteredClientRepository
* @see OAuth2AuthorizationService
* @see OAuth2Authorization
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section 4.1 Authorization Code Grant</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1.1">Section 4.1.1 Authorization Request</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1.2">Section 4.1.2 Authorization Response</a>
*/
public clreplaced OAuth2AuthorizationEndpointFilter extends OncePerRequestFilter {
/**
* The default endpoint {@code URI} for authorization requests.
*/
public static final String DEFAULT_AUTHORIZATION_ENDPOINT_URI = "/oauth2/authorize";
private static final OAuth2TokenType STATE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.STATE);
private static final String PKCE_ERROR_URI = "https://tools.ietf.org/html/rfc7636#section-4.4.1";
private final RegisteredClientRepository registeredClientRepository;
private final OAuth2AuthorizationService authorizationService;
private final RequestMatcher authorizationRequestMatcher;
private final RequestMatcher userConsentMatcher;
private final StringKeyGenerator codeGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 96);
private final StringKeyGenerator stateGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder());
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
/**
* Constructs an {@code OAuth2AuthorizationEndpointFilter} using the provided parameters.
*
* @param registeredClientRepository the repository of registered clients
* @param authorizationService the authorization service
*/
public OAuth2AuthorizationEndpointFilter(RegisteredClientRepository registeredClientRepository, OAuth2AuthorizationService authorizationService) {
this(registeredClientRepository, authorizationService, DEFAULT_AUTHORIZATION_ENDPOINT_URI);
}
/**
* Constructs an {@code OAuth2AuthorizationEndpointFilter} using the provided parameters.
*
* @param registeredClientRepository the repository of registered clients
* @param authorizationService the authorization service
* @param authorizationEndpointUri the endpoint {@code URI} for authorization requests
*/
public OAuth2AuthorizationEndpointFilter(RegisteredClientRepository registeredClientRepository, OAuth2AuthorizationService authorizationService, String authorizationEndpointUri) {
replacedert.notNull(registeredClientRepository, "registeredClientRepository cannot be null");
replacedert.notNull(authorizationService, "authorizationService cannot be null");
replacedert.hasText(authorizationEndpointUri, "authorizationEndpointUri cannot be empty");
this.registeredClientRepository = registeredClientRepository;
this.authorizationService = authorizationService;
RequestMatcher authorizationRequestGetMatcher = new AntPathRequestMatcher(authorizationEndpointUri, HttpMethod.GET.name());
RequestMatcher authorizationRequestPostMatcher = new AntPathRequestMatcher(authorizationEndpointUri, HttpMethod.POST.name());
RequestMatcher openidScopeMatcher = request -> {
String scope = request.getParameter(OAuth2ParameterNames.SCOPE);
return StringUtils.hasText(scope) && scope.contains(OidcScopes.OPENID);
};
RequestMatcher consentActionMatcher = request -> request.getParameter(UserConsentPage.CONSENT_ACTION_PARAMETER_NAME) != null;
this.authorizationRequestMatcher = new OrRequestMatcher(authorizationRequestGetMatcher, new AndRequestMatcher(authorizationRequestPostMatcher, openidScopeMatcher, new NegatedRequestMatcher(consentActionMatcher)));
this.userConsentMatcher = new AndRequestMatcher(authorizationRequestPostMatcher, consentActionMatcher);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (this.authorizationRequestMatcher.matches(request)) {
processAuthorizationRequest(request, response, filterChain);
} else if (this.userConsentMatcher.matches(request)) {
processUserConsent(request, response);
} else {
filterChain.doFilter(request, response);
}
}
private void processAuthorizationRequest(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
OAuth2AuthorizationRequestContext authorizationRequestContext = new OAuth2AuthorizationRequestContext(request.getRequestURL().toString(), OAuth2EndpointUtils.getParameters(request));
validateAuthorizationRequest(authorizationRequestContext);
if (authorizationRequestContext.hasError()) {
if (authorizationRequestContext.isRedirectOnError()) {
sendErrorResponse(request, response, authorizationRequestContext.resolveRedirectUri(), authorizationRequestContext.getError(), authorizationRequestContext.getState());
} else {
sendErrorResponse(response, authorizationRequestContext.getError());
}
return;
}
// ---------------
// The request is valid - ensure the resource owner is authenticated
// ---------------
Authentication principal = SecurityContextHolder.getContext().getAuthentication();
if (!isPrincipalAuthenticated(principal)) {
// Preplaced through the chain with the expectation that the authentication process
// will commence via AuthenticationEntryPoint
filterChain.doFilter(request, response);
return;
}
RegisteredClient registeredClient = authorizationRequestContext.getRegisteredClient();
OAuth2AuthorizationRequest authorizationRequest = authorizationRequestContext.buildAuthorizationRequest();
OAuth2Authorization.Builder builder = OAuth2Authorization.withRegisteredClient(registeredClient).principalName(principal.getName()).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).attribute(Principal.clreplaced.getName(), principal).attribute(OAuth2AuthorizationRequest.clreplaced.getName(), authorizationRequest);
if (requireUserConsent(registeredClient, authorizationRequest)) {
String state = this.stateGenerator.generateKey();
OAuth2Authorization authorization = builder.attribute(OAuth2ParameterNames.STATE, state).build();
this.authorizationService.save(authorization);
// TODO Need to remove 'in-flight' authorization if consent step is not completed (e.g. approved or cancelled)
UserConsentPage.displayConsent(request, response, registeredClient, authorization);
} else {
Instant issuedAt = Instant.now();
// TODO Allow configuration for authorization code time-to-live
Instant expiresAt = issuedAt.plus(5, ChronoUnit.MINUTES);
OAuth2AuthorizationCode authorizationCode = new OAuth2AuthorizationCode(this.codeGenerator.generateKey(), issuedAt, expiresAt);
OAuth2Authorization authorization = builder.token(authorizationCode).attribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME, authorizationRequest.getScopes()).build();
this.authorizationService.save(authorization);
// TODO security checks for code parameter
// The authorization code MUST expire shortly after it is issued to mitigate the risk of leaks.
// A maximum authorization code lifetime of 10 minutes is RECOMMENDED.
// The client MUST NOT use the authorization code more than once.
// If an authorization code is used more than once, the authorization server MUST deny the request
// and SHOULD revoke (when possible) all tokens previously issued based on that authorization code.
// The authorization code is bound to the client identifier and redirection URI.
sendAuthorizationResponse(request, response, authorizationRequestContext.resolveRedirectUri(), authorizationCode, authorizationRequest.getState());
}
}
private static boolean requireUserConsent(RegisteredClient registeredClient, OAuth2AuthorizationRequest authorizationRequest) {
// openid scope does not require consent
if (authorizationRequest.getScopes().contains(OidcScopes.OPENID) && authorizationRequest.getScopes().size() == 1) {
return false;
}
return registeredClient.getClientSettings().requireUserConsent();
}
private void processUserConsent(HttpServletRequest request, HttpServletResponse response) throws IOException {
UserConsentRequestContext userConsentRequestContext = new UserConsentRequestContext(request.getRequestURL().toString(), OAuth2EndpointUtils.getParameters(request));
validateUserConsentRequest(userConsentRequestContext);
if (userConsentRequestContext.hasError()) {
if (userConsentRequestContext.isRedirectOnError()) {
sendErrorResponse(request, response, userConsentRequestContext.resolveRedirectUri(), userConsentRequestContext.getError(), userConsentRequestContext.getState());
} else {
sendErrorResponse(response, userConsentRequestContext.getError());
}
return;
}
if (!UserConsentPage.isConsentApproved(request)) {
this.authorizationService.remove(userConsentRequestContext.getAuthorization());
OAuth2Error error = createError(OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ParameterNames.CLIENT_ID);
sendErrorResponse(request, response, userConsentRequestContext.resolveRedirectUri(), error, userConsentRequestContext.getAuthorizationRequest().getState());
return;
}
Instant issuedAt = Instant.now();
// TODO Allow configuration for authorization code time-to-live
Instant expiresAt = issuedAt.plus(5, ChronoUnit.MINUTES);
OAuth2AuthorizationCode authorizationCode = new OAuth2AuthorizationCode(this.codeGenerator.generateKey(), issuedAt, expiresAt);
Set<String> authorizedScopes = userConsentRequestContext.getScopes();
if (userConsentRequestContext.getAuthorizationRequest().getScopes().contains(OidcScopes.OPENID)) {
// openid scope is auto-approved as it does not require consent
authorizedScopes.add(OidcScopes.OPENID);
}
OAuth2Authorization authorization = OAuth2Authorization.from(userConsentRequestContext.getAuthorization()).token(authorizationCode).attributes(attrs -> {
attrs.remove(OAuth2ParameterNames.STATE);
attrs.put(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME, authorizedScopes);
}).build();
this.authorizationService.save(authorization);
sendAuthorizationResponse(request, response, userConsentRequestContext.resolveRedirectUri(), authorizationCode, userConsentRequestContext.getAuthorizationRequest().getState());
}
private void validateAuthorizationRequest(OAuth2AuthorizationRequestContext authorizationRequestContext) {
// ---------------
// Validate the request to ensure all required parameters are present and valid
// ---------------
// client_id (REQUIRED)
if (!StringUtils.hasText(authorizationRequestContext.getClientId()) || authorizationRequestContext.getParameters().get(OAuth2ParameterNames.CLIENT_ID).size() != 1) {
authorizationRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID));
return;
}
RegisteredClient registeredClient = this.registeredClientRepository.findByClientId(authorizationRequestContext.getClientId());
if (registeredClient == null) {
authorizationRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID));
return;
} else if (!registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.AUTHORIZATION_CODE)) {
authorizationRequestContext.setError(createError(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT, OAuth2ParameterNames.CLIENT_ID));
return;
}
authorizationRequestContext.setRegisteredClient(registeredClient);
// redirect_uri (OPTIONAL)
if (StringUtils.hasText(authorizationRequestContext.getRedirectUri())) {
if (!registeredClient.getRedirectUris().contains(authorizationRequestContext.getRedirectUri()) || authorizationRequestContext.getParameters().get(OAuth2ParameterNames.REDIRECT_URI).size() != 1) {
authorizationRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI));
return;
}
} else if (// redirect_uri is REQUIRED for OpenID Connect
authorizationRequestContext.isAuthenticationRequest() || registeredClient.getRedirectUris().size() != 1) {
authorizationRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI));
return;
}
authorizationRequestContext.setRedirectOnError(true);
// response_type (REQUIRED)
if (!StringUtils.hasText(authorizationRequestContext.getResponseType()) || authorizationRequestContext.getParameters().get(OAuth2ParameterNames.RESPONSE_TYPE).size() != 1) {
authorizationRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.RESPONSE_TYPE));
return;
} else if (!authorizationRequestContext.getResponseType().equals(OAuth2AuthorizationResponseType.CODE.getValue())) {
authorizationRequestContext.setError(createError(OAuth2ErrorCodes.UNSUPPORTED_RESPONSE_TYPE, OAuth2ParameterNames.RESPONSE_TYPE));
return;
}
// scope (OPTIONAL)
Set<String> requestedScopes = authorizationRequestContext.getScopes();
Set<String> allowedScopes = registeredClient.getScopes();
if (!requestedScopes.isEmpty() && !allowedScopes.containsAll(requestedScopes)) {
authorizationRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_SCOPE, OAuth2ParameterNames.SCOPE));
return;
}
// code_challenge (REQUIRED for public clients) - RFC 7636 (PKCE)
String codeChallenge = authorizationRequestContext.getParameters().getFirst(PkceParameterNames.CODE_CHALLENGE);
if (StringUtils.hasText(codeChallenge)) {
if (authorizationRequestContext.getParameters().get(PkceParameterNames.CODE_CHALLENGE).size() != 1) {
authorizationRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE, PKCE_ERROR_URI));
return;
}
String codeChallengeMethod = authorizationRequestContext.getParameters().getFirst(PkceParameterNames.CODE_CHALLENGE_METHOD);
if (StringUtils.hasText(codeChallengeMethod)) {
if (authorizationRequestContext.getParameters().get(PkceParameterNames.CODE_CHALLENGE_METHOD).size() != 1 || (!"S256".equals(codeChallengeMethod) && !"plain".equals(codeChallengeMethod))) {
authorizationRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE_METHOD, PKCE_ERROR_URI));
return;
}
}
} else if (registeredClient.getClientSettings().requireProofKey()) {
authorizationRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE, PKCE_ERROR_URI));
return;
}
}
private void validateUserConsentRequest(UserConsentRequestContext userConsentRequestContext) {
// ---------------
// Validate the request to ensure all required parameters are present and valid
// ---------------
// state (REQUIRED)
if (!StringUtils.hasText(userConsentRequestContext.getState()) || userConsentRequestContext.getParameters().get(OAuth2ParameterNames.STATE).size() != 1) {
userConsentRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE));
return;
}
OAuth2Authorization authorization = this.authorizationService.findByToken(userConsentRequestContext.getState(), STATE_TOKEN_TYPE);
if (authorization == null) {
userConsentRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE));
return;
}
userConsentRequestContext.setAuthorization(authorization);
// The 'in-flight' authorization must be replacedociated to the current principal
Authentication principal = SecurityContextHolder.getContext().getAuthentication();
if (!isPrincipalAuthenticated(principal) || !principal.getName().equals(authorization.getPrincipalName())) {
userConsentRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE));
return;
}
// client_id (REQUIRED)
if (!StringUtils.hasText(userConsentRequestContext.getClientId()) || userConsentRequestContext.getParameters().get(OAuth2ParameterNames.CLIENT_ID).size() != 1) {
userConsentRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID));
return;
}
RegisteredClient registeredClient = this.registeredClientRepository.findByClientId(userConsentRequestContext.getClientId());
if (registeredClient == null || !registeredClient.getId().equals(authorization.getRegisteredClientId())) {
userConsentRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID));
return;
}
userConsentRequestContext.setRegisteredClient(registeredClient);
userConsentRequestContext.setRedirectOnError(true);
// scope (OPTIONAL)
Set<String> requestedScopes = userConsentRequestContext.getAuthorizationRequest().getScopes();
Set<String> authorizedScopes = userConsentRequestContext.getScopes();
if (!authorizedScopes.isEmpty() && !requestedScopes.containsAll(authorizedScopes)) {
userConsentRequestContext.setError(createError(OAuth2ErrorCodes.INVALID_SCOPE, OAuth2ParameterNames.SCOPE));
return;
}
}
private void sendAuthorizationResponse(HttpServletRequest request, HttpServletResponse response, String redirectUri, OAuth2AuthorizationCode authorizationCode, String state) throws IOException {
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(redirectUri).queryParam(OAuth2ParameterNames.CODE, authorizationCode.getTokenValue());
if (StringUtils.hasText(state)) {
uriBuilder.queryParam(OAuth2ParameterNames.STATE, state);
}
this.redirectStrategy.sendRedirect(request, response, uriBuilder.toUriString());
}
private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response, String redirectUri, OAuth2Error error, String state) throws IOException {
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(redirectUri).queryParam(OAuth2ParameterNames.ERROR, error.getErrorCode());
if (StringUtils.hasText(error.getDescription())) {
uriBuilder.queryParam(OAuth2ParameterNames.ERROR_DESCRIPTION, error.getDescription());
}
if (StringUtils.hasText(error.getUri())) {
uriBuilder.queryParam(OAuth2ParameterNames.ERROR_URI, error.getUri());
}
if (StringUtils.hasText(state)) {
uriBuilder.queryParam(OAuth2ParameterNames.STATE, state);
}
this.redirectStrategy.sendRedirect(request, response, uriBuilder.toUriString());
}
private void sendErrorResponse(HttpServletResponse response, OAuth2Error error) throws IOException {
// TODO Send default html error response
response.sendError(HttpStatus.BAD_REQUEST.value(), error.toString());
}
private static OAuth2Error createError(String errorCode, String parameterName) {
return createError(errorCode, parameterName, "https://tools.ietf.org/html/rfc6749#section-4.1.2.1");
}
private static OAuth2Error createError(String errorCode, String parameterName, String errorUri) {
return new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, errorUri);
}
private static boolean isPrincipalAuthenticated(Authentication principal) {
return principal != null && !AnonymousAuthenticationToken.clreplaced.isreplacedignableFrom(principal.getClreplaced()) && principal.isAuthenticated();
}
private static clreplaced OAuth2AuthorizationRequestContext extends AbstractRequestContext {
private final String responseType;
private final String redirectUri;
private OAuth2AuthorizationRequestContext(String authorizationUri, MultiValueMap<String, String> parameters) {
super(authorizationUri, parameters, parameters.getFirst(OAuth2ParameterNames.CLIENT_ID), parameters.getFirst(OAuth2ParameterNames.STATE), extractScopes(parameters));
this.responseType = parameters.getFirst(OAuth2ParameterNames.RESPONSE_TYPE);
this.redirectUri = parameters.getFirst(OAuth2ParameterNames.REDIRECT_URI);
}
private static Set<String> extractScopes(MultiValueMap<String, String> parameters) {
String scope = parameters.getFirst(OAuth2ParameterNames.SCOPE);
return StringUtils.hasText(scope) ? new HashSet<>(Arrays.asList(StringUtils.delimitedListToStringArray(scope, " "))) : Collections.emptySet();
}
private String getResponseType() {
return this.responseType;
}
private String getRedirectUri() {
return this.redirectUri;
}
private boolean isAuthenticationRequest() {
return getScopes().contains(OidcScopes.OPENID);
}
protected String resolveRedirectUri() {
return StringUtils.hasText(getRedirectUri()) ? getRedirectUri() : getRegisteredClient().getRedirectUris().iterator().next();
}
private OAuth2AuthorizationRequest buildAuthorizationRequest() {
return OAuth2AuthorizationRequest.authorizationCode().authorizationUri(getAuthorizationUri()).clientId(getClientId()).redirectUri(getRedirectUri()).scopes(getScopes()).state(getState()).additionalParameters(additionalParameters -> getParameters().entrySet().stream().filter(e -> !e.getKey().equals(OAuth2ParameterNames.RESPONSE_TYPE) && !e.getKey().equals(OAuth2ParameterNames.CLIENT_ID) && !e.getKey().equals(OAuth2ParameterNames.REDIRECT_URI) && !e.getKey().equals(OAuth2ParameterNames.SCOPE) && !e.getKey().equals(OAuth2ParameterNames.STATE)).forEach(e -> additionalParameters.put(e.getKey(), e.getValue().get(0)))).build();
}
}
private static clreplaced UserConsentRequestContext extends AbstractRequestContext {
private OAuth2Authorization authorization;
private UserConsentRequestContext(String authorizationUri, MultiValueMap<String, String> parameters) {
super(authorizationUri, parameters, parameters.getFirst(OAuth2ParameterNames.CLIENT_ID), parameters.getFirst(OAuth2ParameterNames.STATE), extractScopes(parameters));
}
private static Set<String> extractScopes(MultiValueMap<String, String> parameters) {
List<String> scope = parameters.get(OAuth2ParameterNames.SCOPE);
return !CollectionUtils.isEmpty(scope) ? new HashSet<>(scope) : Collections.emptySet();
}
private OAuth2Authorization getAuthorization() {
return this.authorization;
}
private void setAuthorization(OAuth2Authorization authorization) {
this.authorization = authorization;
}
protected String resolveRedirectUri() {
OAuth2AuthorizationRequest authorizationRequest = getAuthorizationRequest();
return StringUtils.hasText(authorizationRequest.getRedirectUri()) ? authorizationRequest.getRedirectUri() : getRegisteredClient().getRedirectUris().iterator().next();
}
private OAuth2AuthorizationRequest getAuthorizationRequest() {
return getAuthorization().getAttribute(OAuth2AuthorizationRequest.clreplaced.getName());
}
}
private abstract static clreplaced AbstractRequestContext {
private final String authorizationUri;
private final MultiValueMap<String, String> parameters;
private final String clientId;
private final String state;
private final Set<String> scopes;
private RegisteredClient registeredClient;
private OAuth2Error error;
private boolean redirectOnError;
protected AbstractRequestContext(String authorizationUri, MultiValueMap<String, String> parameters, String clientId, String state, Set<String> scopes) {
this.authorizationUri = authorizationUri;
this.parameters = parameters;
this.clientId = clientId;
this.state = state;
this.scopes = scopes;
}
protected String getAuthorizationUri() {
return this.authorizationUri;
}
protected MultiValueMap<String, String> getParameters() {
return this.parameters;
}
protected String getClientId() {
return this.clientId;
}
protected String getState() {
return this.state;
}
protected Set<String> getScopes() {
return this.scopes;
}
protected RegisteredClient getRegisteredClient() {
return this.registeredClient;
}
protected void setRegisteredClient(RegisteredClient registeredClient) {
this.registeredClient = registeredClient;
}
protected OAuth2Error getError() {
return this.error;
}
protected void setError(OAuth2Error error) {
this.error = error;
}
protected boolean hasError() {
return getError() != null;
}
protected boolean isRedirectOnError() {
return this.redirectOnError;
}
protected void setRedirectOnError(boolean redirectOnError) {
this.redirectOnError = redirectOnError;
}
protected abstract String resolveRedirectUri();
}
private static clreplaced UserConsentPage {
private static final MediaType TEXT_HTML_UTF8 = new MediaType("text", "html", StandardCharsets.UTF_8);
private static final String CONSENT_ACTION_PARAMETER_NAME = "consent_action";
private static final String CONSENT_ACTION_APPROVE = "approve";
private static final String CONSENT_ACTION_CANCEL = "cancel";
private static void displayConsent(HttpServletRequest request, HttpServletResponse response, RegisteredClient registeredClient, OAuth2Authorization authorization) throws IOException {
String consentPage = generateConsentPage(request, registeredClient, authorization);
response.setContentType(TEXT_HTML_UTF8.toString());
response.setContentLength(consentPage.getBytes(StandardCharsets.UTF_8).length);
response.getWriter().write(consentPage);
}
private static boolean isConsentApproved(HttpServletRequest request) {
return CONSENT_ACTION_APPROVE.equalsIgnoreCase(request.getParameter(CONSENT_ACTION_PARAMETER_NAME));
}
private static boolean isConsentCancelled(HttpServletRequest request) {
return CONSENT_ACTION_CANCEL.equalsIgnoreCase(request.getParameter(CONSENT_ACTION_PARAMETER_NAME));
}
private static String generateConsentPage(HttpServletRequest request, RegisteredClient registeredClient, OAuth2Authorization authorization) {
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(OAuth2AuthorizationRequest.clreplaced.getName());
Set<String> scopes = new HashSet<>(authorizationRequest.getScopes());
// openid scope does not require consent
scopes.remove(OidcScopes.OPENID);
String state = authorization.getAttribute(OAuth2ParameterNames.STATE);
StringBuilder builder = new StringBuilder();
builder.append("<!DOCTYPE html>");
builder.append("<html lang=\"en\">");
builder.append("<head>");
builder.append(" <meta charset=\"utf-8\">");
builder.append(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">");
builder.append(" <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\" integrity=\"sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z\" crossorigin=\"anonymous\">");
builder.append(" <replacedle>Consent required</replacedle>");
builder.append("</head>");
builder.append("<body>");
builder.append("<div clreplaced=\"container\">");
builder.append(" <div clreplaced=\"py-5\">");
builder.append(" <h1 clreplaced=\"text-center\">Consent required</h1>");
builder.append(" </div>");
builder.append(" <div clreplaced=\"row\">");
builder.append(" <div clreplaced=\"col text-center\">");
builder.append(" <p><span clreplaced=\"font-weight-bold text-primary\">" + registeredClient.getClientId() + "</span> wants to access your account <span clreplaced=\"font-weight-bold\">" + authorization.getPrincipalName() + "</span></p>");
builder.append(" </div>");
builder.append(" </div>");
builder.append(" <div clreplaced=\"row pb-3\">");
builder.append(" <div clreplaced=\"col text-center\">");
builder.append(" <p>The following permissions are requested by the above app.<br/>Please review these and consent if you approve.</p>");
builder.append(" </div>");
builder.append(" </div>");
builder.append(" <div clreplaced=\"row\">");
builder.append(" <div clreplaced=\"col text-center\">");
builder.append(" <form method=\"post\" action=\"" + request.getRequestURI() + "\">");
builder.append(" <input type=\"hidden\" name=\"client_id\" value=\"" + registeredClient.getClientId() + "\">");
builder.append(" <input type=\"hidden\" name=\"state\" value=\"" + state + "\">");
for (String scope : scopes) {
builder.append(" <div clreplaced=\"form-group form-check py-1\">");
builder.append(" <input clreplaced=\"form-check-input\" type=\"checkbox\" name=\"scope\" value=\"" + scope + "\" id=\"" + scope + "\" checked>");
builder.append(" <label clreplaced=\"form-check-label\" for=\"" + scope + "\">" + scope + "</label>");
builder.append(" </div>");
}
builder.append(" <div clreplaced=\"form-group pt-3\">");
builder.append(" <button clreplaced=\"btn btn-primary btn-lg\" type=\"submit\" name=\"consent_action\" value=\"approve\">Submit Consent</button>");
builder.append(" </div>");
builder.append(" <div clreplaced=\"form-group\">");
builder.append(" <button clreplaced=\"btn btn-link regular\" type=\"submit\" name=\"consent_action\" value=\"cancel\">Cancel</button>");
builder.append(" </div>");
builder.append(" </form>");
builder.append(" </div>");
builder.append(" </div>");
builder.append(" <div clreplaced=\"row pt-4\">");
builder.append(" <div clreplaced=\"col text-center\">");
builder.append(" <p><small>Your consent to provide access is required.<br/>If you do not approve, click Cancel, in which case no information will be shared with the app.</small></p>");
builder.append(" </div>");
builder.append(" </div>");
builder.append("</div>");
builder.append("</body>");
builder.append("</html>");
return builder.toString();
}
}
}
15
Source : FebsAuthenticationSucessHandler.java
with Apache License 2.0
from febsteam
with Apache License 2.0
from febsteam
/**
* 登录成功处理器
*/
public clreplaced FebsAuthenticationSucessHandler implements AuthenticationSuccessHandler {
private ObjectMapper mapper = new ObjectMapper();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private SessionRegistry sessionRegistry;
@Autowired
private FebsSecurityProperties febsSecurityProperties;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
String remoteAddress = details.getRemoteAddress();
LoginType loginType = LoginType.normal;
Object principal = authentication.getPrincipal();
if (principal instanceof FebsUserDetails) {
FebsUserDetails userDetails = (FebsUserDetails) principal;
userDetails.setRemoteAddress(remoteAddress);
loginType = userDetails.getLoginType();
}
if (principal instanceof FebsSocialUserDetails) {
FebsSocialUserDetails userDetails = (FebsSocialUserDetails) principal;
userDetails.setRemoteAddress(remoteAddress);
loginType = userDetails.getLoginType();
}
// 解决第三方登录在 session 并发控制设置不生效的问题
if (!LoginType.normal.equals(loginType)) {
String sessionId = details.getSessionId();
sessionRegistry.removeSessionInformation(sessionId);
sessionRegistry.registerNewSession(sessionId, authentication.getPrincipal());
ConcurrentSessionControlAuthenticationStrategy authenticationStrategy = new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry);
// 手动设置最大并发登录数量,因为在 sessionManagement 中设置的 maximumSessions
// 只对账号密码登录的方式生效 =。=
authenticationStrategy.setMaximumSessions(febsSecurityProperties.getSession().getMaximumSessions());
authenticationStrategy.onAuthentication(authentication, request, response);
// 社交账户登录成功后直接 重定向到主页
if (LoginType.social.equals(loginType))
redirectStrategy.sendRedirect(request, response, febsSecurityProperties.getIndexUrl());
}
response.setContentType(FebsConstant.JSON_UTF8);
response.getWriter().write(mapper.writeValuereplacedtring(ResponseBo.ok()));
}
public SessionRegistry getSessionRegistry() {
return sessionRegistry;
}
public void setSessionRegistry(SessionRegistry sessionRegistry) {
this.sessionRegistry = sessionRegistry;
}
}
15
Source : WebSecurityConfig.java
with MIT License
from deadlocker8
with MIT License
from deadlocker8
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public clreplaced WebSecurityConfig extends WebSecurityConfigurerAdapter {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private final UserDetailsService userDetailsService;
private PreLoginUrlBlacklist preLoginUrlBlacklist;
@Autowired
public WebSecurityConfig(UserDetailsServiceImpl userDetailsService) {
this.userDetailsService = userDetailsService;
this.preLoginUrlBlacklist = new PreLoginUrlBlacklist();
}
@Bean
public BCryptPreplacedwordEncoder bCryptPreplacedwordEncoder() {
return new BCryptPreplacedwordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().and().authorizeRequests().antMatchers("/css/**", "/js/**", "/images/**", "/webjars/**", "/favicon.ico").permitAll().antMatchers("/**").authenticated().antMatchers("/login").permitAll().and().formLogin().loginPage("/login").successHandler((req, res, auth) -> {
Object preLoginURL = req.getSession().getAttribute("preLoginURL");
if (preLoginURL == null || preLoginUrlBlacklist.isBlacklisted(preLoginURL.toString())) {
preLoginURL = "/";
}
redirectStrategy.sendRedirect(req, res, preLoginURL.toString());
}).permitAll().and().logout().permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).preplacedwordEncoder(bCryptPreplacedwordEncoder());
}
}
14
Source : DefaultLogoutSuccessHandler.java
with MIT License
from ZeroOrInfinity
with MIT License
from ZeroOrInfinity
/**
* 登出成功处理器, 如要替换此类, 继承后注入 IOC 容器即可
* @author YongWu zheng
* @version V1.0 Created by 2020/6/4 23:20
*/
@Slf4j
public clreplaced DefaultLogoutSuccessHandler implements LogoutSuccessHandler {
protected final RedirectStrategy redirectStrategy;
protected final String logoutSuccessUrl;
protected final LoginProcessType loginProcessType;
@SuppressWarnings("SpringJavaAutowiredMembersInspection")
@Autowired(required = false)
protected UserCache userCache;
public DefaultLogoutSuccessHandler(ClientProperties clientProperties) {
this.loginProcessType = clientProperties.getLoginProcessType();
this.logoutSuccessUrl = clientProperties.getLogoutSuccessUrl();
this.redirectStrategy = new DefaultRedirectStrategy();
}
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
HttpSession session = request.getSession(true);
log.info("登出成功: user={}, ip={}, ua={}, sid={}, sck={}", authentication != null ? authentication.getPrincipal() : "", IpUtil.getRealIp(request), request.getHeader(SecurityConstants.HEADER_USER_AGENT), session.getId(), session.getAttribute(SecurityConstants.SESSION_ENHANCE_CHECK_KEY));
// 清理缓存
session.removeAttribute(SecurityConstants.SESSION_ENHANCE_CHECK_KEY);
if (userCache != null && authentication != null) {
userCache.removeUserFromCache(authentication.getName());
}
redirectProcessingLogoutByLoginProcessType(request, response, this.logoutSuccessUrl, this.loginProcessType, redirectStrategy, ErrorCodeEnum.LOGOUT_SUCCESS);
}
}
14
Source : HelloController.java
with Apache License 2.0
from xuyisu
with Apache License 2.0
from xuyisu
@RestController
@Slf4j
public clreplaced HelloController {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private RequestCache requestCache = new HttpSessionRequestCache();
@Autowired
private SecurityProperties securityProperties;
/**
* 当需要身份认证时,跳转到这里
*
* @param request
* @param response
* @return
* @throws IOException
*/
@RequestMapping("/authentication/require")
public FwResult requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
String targetUrl = savedRequest.getRedirectUrl();
log.info("引发跳转的请求是:" + targetUrl);
if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
}
}
return FwResult.failed("访问的服务需要身份认证,请引导用户到登录页");
}
/**
* 获取用户信息
*
* @return
*/
@RequestMapping("/user")
public FwResult getUser() {
List<Map<String, String>> maps = new ArrayList<>();
Map<String, String> map = new HashMap<>();
map.put("username", "李四");
map.put("sex", "男");
maps.add(map);
return FwResult.ok(maps);
}
}
14
Source : HelloController.java
with Apache License 2.0
from xuyisu
with Apache License 2.0
from xuyisu
/**
* @author xuyisu
* @description
* @date 2020/04/11
*/
@RestController
@Slf4j
public clreplaced HelloController {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private RequestCache requestCache = new HttpSessionRequestCache();
@Autowired
private SecurityProperties securityProperties;
/**
* 当需要身份认证时,跳转到这里
*
* @param request
* @param response
* @return
* @throws IOException
*/
@RequestMapping("/authentication/require")
public FwResult requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
String targetUrl = savedRequest.getRedirectUrl();
log.info("引发跳转的请求是:" + targetUrl);
if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
}
}
return FwResult.failed("访问的服务需要身份认证,请重新登录");
}
/**
* 获取用户信息
*
* @return
*/
@RequestMapping("/user")
public FwResult getUser() {
List<Map<String, String>> maps = new ArrayList<>();
Map<String, String> map = new HashMap<>();
map.put("username", "李四");
map.put("sex", "男");
maps.add(map);
return FwResult.ok(maps);
}
}
14
Source : BrowserSecurityController.java
with Apache License 2.0
from woodwhales
with Apache License 2.0
from woodwhales
@Slf4j
@RestController
public clreplaced BrowserSecurityController {
// 原请求信息的缓存及恢复
private RequestCache requestCache = new HttpSessionRequestCache();
// 用于重定向
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Autowired
private SecurityProperties securityProperties;
/**
* 当需要身份认证的时候,跳转过来
* @param request
* @param response
* @return
*/
@RequestMapping(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
public BaseResponse requireAuthenication(HttpServletRequest request, HttpServletResponse response) throws IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (Objects.isNull(savedRequest)) {
String targetUrl = savedRequest.getRedirectUrl();
log.info("引发跳转的请求是:" + targetUrl);
if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
}
}
return new BaseResponse("访问的服务需要身份认证,请引导用户到登录页");
}
@GetMapping("/session/invalid")
@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
public BaseResponse sessionInvalid() {
return new BaseResponse("Session 超时");
}
}
14
Source : SessionTimeoutFilter.java
with Mozilla Public License 2.0
from secdec
with Mozilla Public License 2.0
from secdec
public clreplaced SessionTimeoutFilter extends GenericFilterBean {
private final static Integer MAX_TIMEOUT = 30;
private final static Integer MIN_TIMEOUT = 1;
@Autowired
SessionRegistry sessionRegistry;
@Autowired
DefaultConfigService defaultConfigService;
private String expiredUrl;
private LogoutHandler[] handlers = new LogoutHandler[] { new SecurityContextLogoutHandler() };
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
Map<String, Calendar> sessionRefreshTimes = map();
public SessionTimeoutFilter() {
expiredUrl = "/login.jsp";
}
public SessionTimeoutFilter(String expiredUrl) {
this.expiredUrl = expiredUrl;
}
@Override
public void afterPropertiesSet() {
replacedert.notNull(sessionRegistry, "SessionRegistry required");
replacedert.isTrue(expiredUrl == null || UrlUtils.isValidRedirectUrl(expiredUrl), expiredUrl + " isn't a valid redirect URL");
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
if (session != null) {
SessionInformation info = sessionRegistry.getSessionInformation(session.getId());
Calendar lastRefreshTime = sessionRefreshTimes.get(session.getId());
if (lastRefreshTime == null) {
lastRefreshTime = Calendar.getInstance();
sessionRefreshTimes.put(session.getId(), lastRefreshTime);
}
if (info != null) {
if (!info.isExpired()) {
Calendar timeoutThreshold = determineTimeoutThreshold();
if (timeoutThreshold.getTimeInMillis() > lastRefreshTime.getTimeInMillis()) {
info.expireNow();
doLogout(request, response);
String targetUrl = determineExpiredUrl(request, info);
if (targetUrl != null) {
redirectStrategy.sendRedirect(request, response, targetUrl);
return;
} else {
response.getWriter().print("This session has been expired due to inactivity.");
response.flushBuffer();
}
return;
} else {
String requestURI = request.getRequestURI();
if (determineIfURIIsRefreshing(requestURI)) {
sessionRefreshTimes.put(session.getId(), Calendar.getInstance());
}
}
}
}
}
chain.doFilter(request, response);
}
protected String determineExpiredUrl(HttpServletRequest request, SessionInformation info) {
return expiredUrl;
}
protected Calendar determineTimeoutThreshold() {
Calendar timeoutThreshold = Calendar.getInstance();
DefaultConfiguration config = defaultConfigService.loadCurrentConfiguration();
Integer sessionTimeout = config.getSessionTimeout();
if (sessionTimeout != null) {
sessionTimeout = (sessionTimeout > MAX_TIMEOUT || sessionTimeout < MIN_TIMEOUT) ? MAX_TIMEOUT : sessionTimeout;
} else {
sessionTimeout = MAX_TIMEOUT;
}
timeoutThreshold.add(Calendar.MINUTE, -1 * sessionTimeout);
return timeoutThreshold;
}
protected boolean determineIfURIIsRefreshing(String uri) {
// TODO: implement better logic here. We could have a list of regexes to match against
if (uri.contains("/history/recent/") && uri.contains("/history/objects")) {
return false;
}
return true;
}
private void doLogout(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
for (LogoutHandler handler : handlers) {
handler.logout(request, response, auth);
}
}
public void setExpiredUrl(String expiredUrl) {
replacedert.isTrue(expiredUrl == null || UrlUtils.isValidRedirectUrl(expiredUrl), expiredUrl + " isn't a valid redirect URL");
this.expiredUrl = expiredUrl;
}
public void setLogoutHandlers(LogoutHandler[] handlers) {
replacedert.notNull(handlers);
this.handlers = handlers;
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
}
14
Source : BrowserSecurityController.java
with Apache License 2.0
from huifer
with Apache License 2.0
from huifer
/**
* 描述:
*
* @author: huifer
* @date: 2019-11-17
*/
@RestController
public clreplaced BrowserSecurityController {
private Logger log = LoggerFactory.getLogger(getClreplaced());
private RequestCache requestCache = new HttpSessionRequestCache();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Autowired
private SecurityProperties securityProperties;
@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
@RequestMapping("/auth/require")
public Response requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
String target = savedRequest.getRedirectUrl();
log.info("goto = {}", target);
if (StringUtils.endsWithIgnoreCase(target, "html")) {
redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
}
}
return new Response("访问地址需要身份认证");
}
}
14
Source : LoginController.java
with Apache License 2.0
from febsteam
with Apache License 2.0
from febsteam
@Controller
public clreplaced LoginController {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private Logger log = LoggerFactory.getLogger(this.getClreplaced());
private RequestCache requestCache = new HttpSessionRequestCache();
@Autowired
private FebsSecurityProperties febsSecurityProperties;
@GetMapping("/login")
public String login(HttpServletRequest request, HttpServletResponse response) {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
String redirectUrl = savedRequest.getRedirectUrl();
log.info("引发跳转的请求是:{}", redirectUrl);
}
return "login";
}
@GetMapping("/")
public void success(HttpServletRequest request, HttpServletResponse response) throws IOException {
redirectStrategy.sendRedirect(request, response, febsSecurityProperties.getIndexUrl());
}
@GetMapping("index")
public String index(Authentication authentication, Model model) {
model.addAttribute("user", authentication.getPrincipal());
return "index";
}
}
14
Source : BrowserSecurityController.java
with Apache License 2.0
from charlieDJ
with Apache License 2.0
from charlieDJ
@RestController
public clreplaced BrowserSecurityController {
private Logger logger = LoggerFactory.getLogger(getClreplaced());
private RequestCache requestCache = new HttpSessionRequestCache();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Autowired
private SecurityProperties properties;
/**
* 当需要身份认证时跳转到这个controller
*
* @param request
* @param response
* @return
*/
@RequestMapping("/authentication/require")
public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
String targetUrl = savedRequest.getRedirectUrl();
logger.info("引发跳转的请求是:" + targetUrl);
if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
redirectStrategy.sendRedirect(request, response, properties.getBrowser().getLoginPage());
}
}
return new SimpleResponse("访问的服务器需要身份认证,请引导用户到登录页面");
}
}
14
Source : ImoocAuthenticationSuccessHandler.java
with Apache License 2.0
from charlieDJ
with Apache License 2.0
from charlieDJ
@Component("imoocAuthenticationSuccessHandler")
public clreplaced ImoocAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
private Logger logger = LoggerFactory.getLogger(getClreplaced());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Autowired
private ObjectMapper objectMapper;
@Autowired
private SecurityProperties securityProperties;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
logger.info("登录成功");
if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValuereplacedtring(authentication));
} else {
// redirectStrategy.sendRedirect(request,response,"/index1.html");
super.onAuthenticationSuccess(request, response, authentication);
}
}
}
13
Source : Auth2DefaultRequestRedirectFilter.java
with MIT License
from ZeroOrInfinity
with MIT License
from ZeroOrInfinity
/**
* 构建第三方授权链接并重定向
*
* @author Joe Grandja
* @author Rob Winch
* @author YongWu zheng
* @since 5.0
* @see OAuth2AuthorizationRequest
* @see Auth2DefaultRequestResolver
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section
* 4.1 Authorization Code Grant</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.1">Section 4.1.1 Authorization Request
* (Authorization Code)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.2">Section
* 4.2 Implicit Grant</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.2.1">Section 4.2.1 Authorization Request
* (Implicit)</a>
*/
@SuppressWarnings({ "unused", "JavaDoc" })
public clreplaced Auth2DefaultRequestRedirectFilter extends OncePerRequestFilter {
private final Throwablereplacedyzer throwablereplacedyzer = new DefaultThrowablereplacedyzer();
private final RedirectStrategy authorizationRedirectStrategy = new DefaultRedirectStrategy();
private final Auth2DefaultRequestResolver authorizationRequestResolver;
private final Auth2StateCoder auth2StateCoder;
private final SimpleUrlAuthenticationFailureHandler authenticationFailureHandler;
private RequestCache requestCache = new HttpSessionRequestCache();
private final TenantContextHolder tenantContextHolder;
/**
* Constructs an {@code Auth2DefaultRequestRedirectFilter} using the provided
* parameters.
* @param authorizationRequestBaseUri the base {@code URI} used for authorization
* requests
* @param auth2StateCoder state 的编解码器
* @param tenantContextHolder 多租户处理器
* @param authenticationFailureHandler 失败处理器
*/
public Auth2DefaultRequestRedirectFilter(@NonNull String authorizationRequestBaseUri, @Nullable Auth2StateCoder auth2StateCoder, @Nullable TenantContextHolder tenantContextHolder, @NonNull SimpleUrlAuthenticationFailureHandler authenticationFailureHandler) {
replacedert.hasText(authorizationRequestBaseUri, "authorizationRequestBaseUri cannot be empty");
this.authorizationRequestResolver = new Auth2DefaultRequestResolver(authorizationRequestBaseUri);
this.auth2StateCoder = auth2StateCoder;
this.authenticationFailureHandler = authenticationFailureHandler;
this.tenantContextHolder = tenantContextHolder;
}
/**
* Constructs an {@code Auth2DefaultRequestRedirectFilter} using the provided
* parameters.
* @param authorizationRequestResolver the resolver used for resolving authorization
* requests
* @param auth2StateCoder state 的编解码器
* @param tenantContextHolder 多租户处理器
* @param authenticationFailureHandler 失败处理器
* @since 5.1
*/
public Auth2DefaultRequestRedirectFilter(@NonNull Auth2DefaultRequestResolver authorizationRequestResolver, @Nullable Auth2StateCoder auth2StateCoder, @Nullable TenantContextHolder tenantContextHolder, @NonNull SimpleUrlAuthenticationFailureHandler authenticationFailureHandler) {
replacedert.notNull(authorizationRequestResolver, "authorizationRequestResolver cannot be null");
this.authorizationRequestResolver = authorizationRequestResolver;
this.auth2StateCoder = auth2StateCoder;
this.authenticationFailureHandler = authenticationFailureHandler;
this.tenantContextHolder = tenantContextHolder;
}
/**
* Sets the {@link RequestCache} used for storing the current request before
* redirecting the OAuth 2.0 Authorization Request.
* @param requestCache the cache used for storing the current request
*/
public final void setRequestCache(RequestCache requestCache) {
replacedert.notNull(requestCache, "requestCache cannot be null");
this.requestCache = requestCache;
}
@Override
protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
try {
Auth2DefaultRequest authorizationRequest = this.authorizationRequestResolver.resolve(request);
if (authorizationRequest != null) {
if (this.tenantContextHolder != null) {
this.tenantContextHolder.tenantIdHandle(request, null);
}
this.sendRedirectForAuthorization(request, response, authorizationRequest);
return;
}
} catch (Auth2Exception ex) {
this.authenticationFailureHandler.onAuthenticationFailure(request, response, ex);
return;
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
this.unsuccessfulRedirectForAuthorization(request, response, ex);
return;
}
try {
filterChain.doFilter(request, response);
} catch (IOException ex) {
throw ex;
} catch (Exception ex) {
// Check to see if we need to handle ClientAuthorizationRequiredException
Throwable[] causeChain = this.throwablereplacedyzer.determineCauseChain(ex);
AuthenticationException authzEx = (AuthenticationException) this.throwablereplacedyzer.getFirstThrowableOfType(AuthenticationException.clreplaced, causeChain);
if (authzEx != null) {
throw authzEx;
}
if (ex instanceof ServletException) {
throw (ServletException) ex;
}
// noinspection ConstantConditions
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
throw new RuntimeException(ex);
}
}
private void sendRedirectForAuthorization(HttpServletRequest request, HttpServletResponse response, Auth2DefaultRequest authorizationRequest) throws IOException {
String state = authorizationRequest.generateState();
if (this.auth2StateCoder != null) {
// 对 state 进行自定义编码 https://gitee.com/pcore/just-auth-spring-security-starter/issues/I22JC7
state = this.auth2StateCoder.encode(state, request);
}
String authorize = authorizationRequest.authorize(state);
if (isAjaxOrJson(request)) {
responseWithJson(response, HttpStatus.OK.value(), toJsonString(redirect(authorize)));
return;
}
this.authorizationRedirectStrategy.sendRedirect(request, response, authorize);
}
private void unsuccessfulRedirectForAuthorization(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException {
this.logger.error(LogMessage.format("Authorization Request failed: %s", ex, ex));
response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
private static final clreplaced DefaultThrowablereplacedyzer extends Throwablereplacedyzer {
@Override
protected void initExtractorMap() {
super.initExtractorMap();
registerExtractor(ServletException.clreplaced, (throwable) -> {
Throwablereplacedyzer.verifyThrowableHierarchy(throwable, ServletException.clreplaced);
return ((ServletException) throwable).getRootCause();
});
}
}
}
See More Examples