Spring Security(六):カスタムログイン成功と失敗処理
基本的な考え方:Authentication Success HandlerまたはAuthentication Failure Handlerインターフェースを実現し、対応する構成をすればいいです.もちろん、フレームにはデフォルトの実装クラスがあります.実現クラスを引き継いで自分の業務をカスタマイズすることもできます.
操作の流れ
1、【zjj-security-demoプロジェクト】修正appication.yml
属性のloging Pageをブロックして、後のテスト用に使用します.属性のlogin Typeを追加して登録に成功して戻ってきたのはジャンプページですか?それともJSONに戻りますか?
2、【zjj-security-coreプロジェクト】BrowserProperties配置類、対応属性を追加します.
3、【zjj-security-coreプロジェクト】エニュメレーション類を追加し、登録して戻るタイプを設定します.
ログイン成功処理
1、【zjj-security-brooswerプロジェクト】新規類を作成し、Authentication Success Handlerインターフェースを実現し、または関連の実現類を継承する.
必要に応じて戻ります.
a、zjj-security-demoプロジェクトのappration.ymlのzjj.security.browser.loginType=REDIRECTを設定する アクセス http://localhost:8080/index.htmlを選択します.ログインが成功したら戻ります. http://localhost:8080/index.html を選択して印刷します
ログイン失敗処理
1、【zjj-security-brooswerプロジェクト】新規類を作成し、Authentication Success Handlerインターフェースを実現し、または関連の実現類を継承する.
必要に応じて戻ります.
a、zjj-security-demoプロジェクトのappration.ymlのzjj.security.browser.loginType=REDIRECTを設定する アクセス http://localhost:8080/index.htmlを選択します.ログインに失敗したら戻ります. http://localhost:8080/authentication/form を選択して印刷します
詳細は私の個人ブログに注目してください.http://www.zjjfx68.com/
操作の流れ
1、【zjj-security-demoプロジェクト】修正appication.yml
属性のloging Pageをブロックして、後のテスト用に使用します.属性のlogin Typeを追加して登録に成功して戻ってきたのはジャンプページですか?それともJSONに戻りますか?
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/xxx?useUnicode=true&characterEncoding=utf-8&useSSL=false
username:
password:
# session
session:
store-type: none
# spring security true
security:
basic:
enabled: true
# html
zjj:
security:
browser:
# loginPage, loginType JSON
# loginPage: /demo-sign.html
loginType: REDIRECT
2、【zjj-security-coreプロジェクト】BrowserProperties配置類、対応属性を追加します.
package com.zjj.security.core.properties;
public class BrowserProperties {
// loginPage = "/zjj-login.html": zjj-security-demo zjj.security.browser.loginPage
private String loginPage = "/zjj-login.html";
//
private LoginResponseType loginType = LoginResponseType.JSON;
public String getLoginPage() {
return loginPage;
}
public void setLoginPage(String loginPage) {
this.loginPage = loginPage;
}
public LoginResponseType getLoginType() {
return loginType;
}
public void setLoginType(LoginResponseType loginType) {
this.loginType = loginType;
}
}
3、【zjj-security-coreプロジェクト】エニュメレーション類を追加し、登録して戻るタイプを設定します.
package com.zjj.security.core.properties;
public enum LoginResponseType {
/**
*
*/
REDIRECT,
/**
* json
*/
JSON
}
ログイン成功処理
1、【zjj-security-brooswerプロジェクト】新規類を作成し、Authentication Success Handlerインターフェースを実現し、または関連の実現類を継承する.
必要に応じて戻ります.
package com.zjj.security.browser.authentication;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjj.security.core.properties.LoginResponseType;
import com.zjj.security.core.properties.SecurityProperties;
@Component("zjjAuthenticationSuccessHandler")
public class ZjjAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private ObjectMapper objectMapper;
@Autowired
private SecurityProperties securityProperties;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
logger.info(" ");
if (LoginResponseType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(authentication));
} else {
super.onAuthenticationSuccess(request, response, authentication);
}
}
}
2、【zjj-security-brooswerプロジェクト】config類定義ユーザー登録成功の処理package com.zjj.security.browser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.zjj.security.browser.authentication.ZjjAuthenticationFailureHandler;
import com.zjj.security.browser.authentication.ZjjAuthenticationSuccessHandler;
import com.zjj.security.core.properties.SecurityProperties;
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SecurityProperties securityProperties;
@Autowired
private ZjjAuthenticationSuccessHandler zjjAuthenticationSuccessHandler;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //
.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form") //
.successHandler(zjjAuthenticationSuccessHandler) //
.and()
.authorizeRequests() //
.antMatchers("/authentication/require", securityProperties.getBrowser().getLoginPage()).permitAll()
.anyRequest() //
.authenticated() //
.and()
.csrf().disable(); // csrf
}
}
3、【zjj-security-demoプロジェクト】は\src\main\resourceの下にフォルダreourcesを新規作成し、index.ページを作成します.
index
index
4、【 zjj-security-demoプロジェクト 】ZjSecurity Demoplication類mainを起動する方法a、zjj-security-demoプロジェクトのappration.ymlのzjj.security.browser.loginType=REDIRECTを設定する アクセス http://localhost:8080/index.htmlを選択します.ログインが成功したら戻ります. http://localhost:8080/index.html を選択して印刷します
index
b、zjj-security-demoプロジェクトのappration.ymlのzjj.security.browser.loginType=JSONを設定する. アクセス http://localhost:8080/index.htmlを選択します.ログインが成功したら、ページが印刷されます.{
"authorities": [{
"authority": "admin"
}],
"details": {
"remoteAddress": "0:0:0:0:0:0:0:1",
"sessionId": "CFC97202A3E9F18084DD5C1E977CF0DA"
},
"authenticated": true,
"principal": {
"password": null,
"username": "zjj",
"authorities": [{
"authority": "admin"
}],
"accountNonExpired": true,
"accountNonLocked": true,
"credentialsNonExpired": true,
"enabled": true
},
"credentials": null,
"name": "zjj"
}
ログイン失敗処理
1、【zjj-security-brooswerプロジェクト】新規類を作成し、Authentication Success Handlerインターフェースを実現し、または関連の実現類を継承する.
必要に応じて戻ります.
package com.zjj.security.browser.authentication;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjj.security.core.properties.LoginResponseType;
import com.zjj.security.core.properties.SecurityProperties;
@Component("zjjAuthenticationFailureHandler")
public class ZjjAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private ObjectMapper objectMapper;
@Autowired
private SecurityProperties securityProperties;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
logger.info(" ");
if (LoginResponseType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
//
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(exception.getMessage()));
} else {
super.onAuthenticationFailure(request, response, exception);
}
}
}
2、【zjj-security-brooswerプロジェクト】config類定義ユーザー登録失敗の処理package com.zjj.security.browser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.zjj.security.browser.authentication.ZjjAuthenticationFailureHandler;
import com.zjj.security.browser.authentication.ZjjAuthenticationSuccessHandler;
import com.zjj.security.core.properties.SecurityProperties;
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SecurityProperties securityProperties;
@Autowired
private ZjjAuthenticationSuccessHandler zjjAuthenticationSuccessHandler;
@Autowired
private ZjjAuthenticationFailureHandler zjjAuthenticationFailureHandler;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //
.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form") //
.successHandler(zjjAuthenticationSuccessHandler) //
.failureHandler(zjjAuthenticationFailureHandler) //
.and()
.authorizeRequests() //
.antMatchers("/authentication/require", securityProperties.getBrowser().getLoginPage()).permitAll()
.anyRequest() //
.authenticated() //
.and()
.csrf().disable(); // csrf
}
}
3、【 zjj-security-demoプロジェクト 】ZjSecurity Demoplication類mainを起動する方法a、zjj-security-demoプロジェクトのappration.ymlのzjj.security.browser.loginType=REDIRECTを設定する アクセス http://localhost:8080/index.htmlを選択します.ログインに失敗したら戻ります. http://localhost:8080/authentication/form を選択して印刷します
There was an unexpected error (type=Unauthorized, status=401).
Authentication Failed:
b、zjj-security-demoプロジェクトのappration.ymlのzjj.security.browser.loginType=JSONを設定する. アクセス http://localhost:8080/index.htmlを選択します.ログインに失敗したら戻ります. http://localhost:8080/authentication/form を選択して印刷します" "
ソースのダウンロードSpring Securityコードクラウドディレクトリ一覧詳細は私の個人ブログに注目してください.http://www.zjjfx68.com/