A segurança da primavera é um módulo grande, e este artigo envolve apenas a autenticação de parâmetros personalizados. Os parâmetros de verificação padrão do Spring Security são apenas nome de usuário e senha, que geralmente não são suficientes. Como o tempo passou por muito tempo, alguns esquecem e outros podem estar faltando. OK, sem bobagens.
As configurações de segurança da primavera e da primavera usam Javaconfig, e as versões são 4.2.5 e 4.0.4 por sua vez.
Ideia geral: personalize o ponto de entretenimento, adicione parâmetros personalizados para estender a autenticaçãoToken e o AuthenticationProvider para verificação.
Primeiro defina o ponto de entrada:
importar org.springframework.security.core.authenticationException; importar org.springframework.security.web.authentication.loginurlauthenticationEntryPoint; importação javax.Servlet.ServleTexception; import Javax.Servlet.Iport.http.HttP.ThTPS. javax.servlet.http.httpServletResponse; importar java.io.ioException; classe pública myauthenticationEntrypoint estende LoginurlauthenticationEntryPoint {public myAuthenticationEntryPoint (string Loginformurl) {super (loginformurl); } @Override public void Comence (solicitação httpServletRequest, resposta httpSertletResponse, autenticaçãoException AuthException) lança IoException, servletexception {super.commência (solicitação, resposta, autexception); }}Em seguida, é o Token, o ValidCode é o parâmetro de código de verificação:
importar org.springframework.security.authentication.UsernamePassWordAthenticationToken; Public Classe MyusernamePasswordAtHenticationToken estende UsernamePasswordAthenticationToken {private String validCode; public myusernamePasswordAthenticationToken (String Principal, String Credenciais, String validCode) {super (principal, credenciais); this.validcode = validCode; } public string getValidCode () {return validCode; } public void SetValidCode (String validCode) {this.validcode = validCode; }}Continue ProcessingFilter,
importação com.core.shared.validatecodeHandle; importar org.springframework.security.core.authentication; importação org.springframework.security.core.authenticationException; importação org.springframework.security.web.authentication.AbstractionationAnticationAnticationAnticationAnticationAnticationic. org.springframework.security.web.util.matcher.antPathRequestMatcher; importar javax.servlet.servletexception; import javax.servlet.http.httpservletReQuest; ImportsOx.ervlet.http.httletRetRetRetReQuest; ImportsOx.Servlet.httP.HttletRetRestReBest; javax.servlet.http.httpSession; importar java.io.ioException; public classe myValidCodeProcessingFilter estende abstrateAuthenticationProcessingFilter {private string userNameparam = "nome de usuário"; Private String senha PasswordParam = "Senha"; private string validCodeParam = "validateCode"; public myValidCodeProcessingFilter () {super (novo AntPathRequestMatcher ("/user/login", "post")); } @Override Autenticação pública Tentação de autenticação (solicitação httpServletRequest, resposta httpSertletResponse) lança autenticaçãoException, ioexception, servletexception {string userName = request.getParameter (UserNameParam); String senha = request.getParameter (PasswordParam); String validCode = request.getParameter (validCodeParam); válido (validCode, request.getSession ()); MyusernamePasswordAuthenticationToken Token = new MyusernamePassWordAuthenticationToken (nome de usuário, senha, validCode); return this.GetaThenticationManager (). Authenticate (token); } public void válido (String validCode, sessão httpSession) {if (validCode == null) {lança new ValidCodeErROREXCECCECCECTION ("ValidAtecode está vazio!"); } if (! validateCodeHandle.matchcode (session.getId (), validCode)) {lança novo validCodeErRorexception ("validCodeError!"); }}} Defina três parâmetros separadamente, que são usados para receber os parâmetros do formulário de login. O método de construção fornece o URL de login e o método de postagem necessário
O próximo é a autenticação. Antes que o nome de usuário e a senha de autenticação tenham chegado, acabei de autenticar o código de verificação.
Aqui está uma classe de ferramenta validateCodeHandle e validCodeErRorexception:
importar java.util.Concurrent.ConcurrentHashMap; public class validateCodeHandle {private estático concorrentehashmap validateCode = new concurrenthashmap <> (); public static concorrentehashmap getCode () {return validateCode; } public static void save (string sessionId, string code) {validatecode.put (sessionId, código); } public static string getValidatecode (String sessionId) {objeto obj = validateCode.get (sessionId); if (obj! = null) {return string.valueof (obj); } retornar nulo; } public static boolean MatchCode (String sessionId, String inputCode) {String SaveCode = getValidatecode (sessionId); if (SaveCode.equals (inputCode)) {return true; } retornar false; }}Aqui você precisa herdar AuthenticationException para indicar que é uma falha de autenticação de segurança, para que o processo de falha subsequente seja seguido.
importar org.springframework.security.core.authenticationException; public class ValdalCodeErRexception estende a autenticaçãoException {public ValdalCodeErRorexception (String msg) {super (msg); } public validCodeErRorexception (String msg, throwable t) {super (msg, t); }}O próximo é o provedor:
importar org.springframework.security.authentication.badcredentialsexception; importação org.springframework.security.authentication.UsernamePasswordAthenticationToken; importação org.springframework.security.authentication.dao.daaAthentationAssationAvadora; org.springframework.security.core.authenticationException; importar org.springframework.security.core.userDetails.userDetails; classe pública myauthenticationProvider estende DaoauthenticationProvider {@Override Bolloolean Apoions (Class <?> MyUsernamePasswordAuthenticationToken.class.isassignablefrom (autenticação); } @Override Protected void adicionalAThenticationChecks (UserDetails UserDetails, UsernamePasswordAthenticationToken Authentication) lança autenticaçãoException {objeto sal = null; if (getSaltsource ()! = null) {Salt = getSaltsource (). getSalt (userDetails); } if (autenticação.getCredentials () == null) {Logger.debug ("Autenticação falhou: nenhuma credenciais fornecidas"); lançar uma nova BadCredentialSexception ("Nome de usuário ou erro de senha!"); } String apresentadoPassword = autenticação.getCredentials (). Tostring (); if (! this.getpasswordEncoder (). isPasswordValid (userDetails.getpassword (), apresentoupassword, sal)) {logger.debug ("Autenticação falhou: a senha não corresponde ao valor armazenado"); lançar uma nova badCredentialSexception ("em nome de usuário ou senha!"); }}} O método de suporte especifica o uso de um token personalizado, e o método adicionalAuthenticationChecks é exatamente o mesmo que a lógica da classe pai, acabei de alterar as informações retornadas pela exceção.
Em seguida é o manipulador que lida com a autenticação bem -sucedida e a autenticação fracassada
importação org.springframework.security.core.authentication; importar org.springframework.security.web.authentication.simplexUthenticationsuccessHandler; importação javax.Servlet.sertleTexception; import Javax.Servlet.Iport.HttP.HtPSPS.HTPSPSPETPETTEX; javax.servlet.http.httpServletResponse; importar java.io.ioException; classe pública FrontesaThenticationsUccessHandler estende SimpleurlauthenticationsUccessHandler {Public FrontetAthenticationsUccessHandler (String defaultTarGetL) {(defaultTargeturl); } @Override vazio público ONAuthenticationsuccess (solicitação httpServletRequest, resposta httpServletResponse, autenticação autenticação) lança ioexception, servletexception {super.onauthenticationsuccess (solicitação, resposta, autenticação); }} importar org.springframework.security.core.authenticationException; importação org.springframework.security.web.authentication.simplexurlauthEnticationFailureHandler; importação; javax.servlet.http.httpServletResponse; importar java.io.ioException; public class FrontetAthenticationFailureHandler estende SimpleurlauthenticationFailureHandler {Public FrontetenticationFailUrHandler (String defaultfailurl) {(defaultFailurl); } @Override public void OnauthenticationFailure (solicitação HttPervLeTrequest, resposta HTTPSERVletResponse, exceção de autenticaçãoException) lança ioexception, servletexception {super.onauthenticationFailure (Solicitação, Resposta, Exceção); }}Finalmente, a configuração de segurança mais importante:
importação com.service.user.customerService; importar com.web.filter.sitemeshfilter; importar com.web.mysecurity. org.springframework.context.annotation.configuration; importar org.springframework.core.annotation.order; importar org.springframework.security.authentication.authenticationManager; importar org.springfamework.security.authentication.authentication; org.springframework.security.authentication.providerManager; importar org.springframework.security.config.annotation.web.builders.httpsecurity; importing.springframework.security.config.annotation.web.confuration org.springframework.security.config.annotation.web.configuration.webescurityConfigureRAdapter; importar org.springframework.security.crypto.password.passwords; org.springframework.security.web.access.exceptionTranslationFilter; importar org.springframework.security.web.authentication.usernamePasswordinAtiAtialFilter; importação org.springFameWorkwork.Security.WEB.ConteticationFilter; ImportstractReCortion org.springframework.web.filter.characterencodingFilter; importar javax.servlet.dispatchertype; importar javax.servlet.filterregistration; importação javax.servlet.servlettontext; import.util.utilist; importação; java.util.list;@configatury@enableweburcuritypublic class securityconfig estende abstractSecurityWebApplicationInitializer {@Bean public senhaNDencoder senha -sencoder () {retorna new StandardPasswordEncoder ("md5"); } @Autowired Private CustomerService CustomerService; @Configuration @Order (1) Classe estática pública FrontendWebUsCurityConfigureAdApter estende WebSecurityConfigureRAdApter {@AUTOWIRED PRIVADO MYVALIDCODEPROCESSINGFILTER myValidCodeProcessingFilter; @Override Protected void Configure (httpsecurity http) lança Exceção {http.csrf (). Desabille () .authorizerequests () .antmatchers ("/user/login", "user/logout"). Permitall () .Yrequest (). .AddfilterBe antes (myValidCodeProcessingFilter, UsernamePasswordAuthenticationFilter.class) .FormLogin () .LoginPage ("/user/login") .and () .Logout () .Logouturl ("/user/login") .LogItSuccessur () .Logouturl ("/user/logout") .LogItSucess }} @Bean (name = "frontetauthenticationProvider") public myAuthenticationProvider FrontetauthenticationProvider () {MyAuthenticationProvider myauthenticationProvider = new MyAuthenticationProvider (); myauthenticationProvider.setUserDetailSService (CustomerService); myauthenticationProvider.SetPasswordEncoder (PasswordEncoder ()); retornar myauthenticationprovider; } @Bean Public AuthenticationManager autenticationManager () {List <ThentaticationProvider> list = new ArrayList <> (); list.add (FrontetauthenticationProvider ()); AuthenticationManager AuthenticationManager = New ProviderManager (List); retornar autenticationManager; } @Bean public myValidCodeProcessingFilter myValidCodeProcessingFilter (autenticação AuthenticationManager) {MyValidCodeProcessingFilter filtro = new MyValidCodeProcessingFilter (); filtro.setAuthenticationManager (autenticaçãoManager); filtro.setAuthenticationsuccessHandler (FrontetauthenticationsuccessHandler ()); filter.setAuthenticationFailureHandler (FrontetauthenticationFailureHandler ()); retorno filtro; } @Bean Public FrontetAthenticationFailureHandler FrentetAthenticationFailureHandler () {return New FrontetAthenticationFailureHandler ("/User/Login"); } @Bean Public FrontetAthenticationsUccessHandler FrontetAtHenticationsUccessHandler () {return New FrontetAtHenticationsUccessHandler ("Frente/Test"); } @Bean public myAuthenticationEntryPoint MyAuthenticationEntryPoint () {return New MyAuthenticationEntryPoint ("/user/login"); }}Primeiro de tudo, é um feijão da aula de criptografia, e o CustomerService é um usuário simples de consulta
@Service ("CustomerService") Classe pública CustomerServiceImpl implementa CustomerService {@AUTOWIRED PRIVADO UserDAO Userdao; @Override public userDetails loadUserByUserName (String UserName) lança UserNameNotFoundException {return userdao.findcustomerbyusername (nome de usuário); }} Em seguida, é o FrontendWebSecurityConfigureadapter. Reescrevi o método de configuração, primeiro desabilite o CSRF, ative o autorizeRequests (), onde "/user/login" e "/user/logout" Let da verificação de permissão, e outras solicitações requerem autenticação de login e, em seguida, addfilterBefore (). Antes de adicionar meu Filter MyValidCodeProcessing Filter personalizado ao Filter de Segurança UsernamePasswordAthentication padrão, primeiro realizo minha autenticação de parâmetros personalizados e depois formALogin (), configure o URL de login e Logout URL e Login URL, Login Url, Login Url e Login Url para Log Outl e Url, que é o Login Url, o Login Url e o Login Url para logout Url, que é o Login Url, e Login Url.
Em seguida, é a declaração de exibição do Bean do autenticaçãoProvider, AuthenticationManager, ProcessingFilter, AuthenticationFailureHandler, AuthenticationsUccessHandler e EntryPoint.
Abaixo está login.jsp
<body> <div> <form: fort autoComplete = "false" commandName = "userdto" method = "post"> <div> <pan> <b> $ {spring_security_last_exception.message} </b> </span> </div> username: <form: input = "username" csScan "csscL. Path = "Senha" CSSCLASS = "Form-Control"/> <br/> ValidAtecode: <form: entus Path = "validateCode" CSSCLASS = "Form-CONTROL"/> LABEL> $ {Validate_code} </Label> <dipl> <bel> <bel> Tipo </tip <Beart_code} "Lembrete"/Div "<bretty> <Beel> <Beart)" Lembre-se <bember) <bret) <brett) <Bael> <bump> <bret> <bump> <brett) <Beat) <bret) <Bael> <but> <but> <Beel> <Bex> <Beart_Code} SUND} </bel> <bel> <bel> <input Type = "Cheque" Nome = "" ME "-ME " value = "submeter"/> </form: form> </div> </body>Quando o código de verificação falha, a validCodeErRorexception é lançada. Como herda a autenticaçãoException, quando a segurança encontra autenticaçãoException, o AuthenticationFailureHandler será acionado. O Bean acima declara que a autenticação falhou e salta para o URL de login; portanto, há $ {spring_security_last_exception.message} em login.jsp. As informações de exceção são lançadas quando eu autentico, o que pode levar ao usuário amigável.
Todo o processo de verificação de segurança personalizado é concluído
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.