当前位置: 首页 > news >正文

专门做护肤品网站ssh网站怎么做

专门做护肤品网站,ssh网站怎么做,淘宝指数网址,百度seo优化方法1、登录表单配置 1.1、快速入门 理解了入门案例之后#xff0c;接下来我们再来看一下登录表单的详细配置#xff0c;首先创建一个新的Spring Boot项目#xff0c;引入Web和Spring Security依赖#xff0c;代码如下#xff1a; dependencygroupIdorg.sp…1、登录表单配置 1.1、快速入门 理解了入门案例之后接下来我们再来看一下登录表单的详细配置首先创建一个新的Spring Boot项目引入Web和Spring Security依赖代码如下 dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-security/artifactId /dependency dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId /dependency项目创建好之后为了方便测试需要在application.yml中添加如下配置将登录用户名和密码固定下来 spring:security:user:name: buretuzipassword: 123456接下来我们在resources/static目录下创建一个login.html页而这个是我们自定义的登录页面 !DOCTYPE html html langen headmeta charsetUTF-8title登录/titlelink href//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css relstylesheet idbootstrap-cssscript src//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js/scriptscript src//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js/script /head style#login .container #login-row #login-column #login-box {border: 1px solid #9c9c9c;background-color: #EAEAEA;} /style bodydiv idlogindiv classcontainerdiv idlogin-row classrow justify-content-center align-items-centerdiv idlogin-column classcol-md-6div idlogin-box classcol-md-12form idlogin-form classform action/dologin methodposth3 classtext-center text-info登录/h3div classform-grouplabel forusername classtext-info用户名/labelbrinput typetext nameuname idusername classform-control/divdiv classform-grouplabel forpassword classtext-info密码/labelbrinput typetext namepasswd idpassword classform-control/divdiv classform-groupinput typesubmit namesubmit classbtn btn-info btn-md value登录/div/form/div/div/div/div/div /body /html这个logmt.html中的核心内容就是一个登录表单登录表单中有三个需要注意的地方 form的action这里给的是/doLogin表示表单要提交到/doLogin接口上。用户名输入框的name属性值为uname,当然这个值是可以自定义的这里采用了uname。密码输入框的name属性值为passwd, passwd也是可以自定义的。 login.html定义好之后接下来定义两个测试接口作为受保护的资源。当用户登录成功 后就可以访问到受保护的资源。接口定义如下 package com.intehel.demo.controller;import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;RestController public class LoginController {RequestMapping(/index)public String index(){return login;}RequestMapping(/hello)public String hello(){return hello;}}最后再提供一个Spring Security的配置类 package com.intehel.demo.config;import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage(/loginNew.html).loginProcessingUrl(/doLogin).defaultSuccessUrl(/index).failureUrl(/loginNew.html).usernameParameter(uname).passwordParameter(passwd).permitAll().and().csrf().disable();}}在Spring Security中如果我们需要自定义配置基本上都是继承自WebSecurityConfigurerAdapter来实现的当然WebSecurityConfigurerAdapter本身的配置还是比较复杂同时也是比较丰富的这里先不做过多的展开仅就结合上面的代码来解释在下节中将会对这里的配置再做更加详细的介绍。 首先configure方法中是一个链式配置当然也可以不用链式配置每一个属性配置完毕后再从重新开始写起;authorizeRequests()方法表示开启权限配置(该方法的含义其实比较复杂在后面还会再次介绍该方法).anyRequest().authenticated()表示所有的请求都要认证之后才能访问;有的读者会对and()方法表示疑惑and()方法会返回HttpSecurityBuilder对象的一个 子类(实际上就是HttpSecurity),所以and()方法相当于又回到HttpSecuiity实例重新开启 新一轮的配置。如果觉得and()方法很难理解也可以不用and()方法在.anyRequest().authenticated。配置完成后直接用分号(;)结束然后通过http.formLogin()继续配置表单登录。formLogin()表示开启表单登录配置loginPage用来配置登录页面地址 loginProcessingUrl用来配置登录接口地址defaultSuccessUrl表示登录成功后的跳转地址 failureUrl表示登录失败后的跳转地址usernameParameter表示登录用户名的参数名称 passwordParameter表示登录密码的参数名称permitAll表示跟登录相关的页面和接口不做拦截, 直接通过。需要注意的是,loginProcessingUrl、usernameParameter、passwordParameter 需要和login-html中登录表单的配置一致。最后的csrf().disable()表示禁用CSRF防御功能Spring Security自带了 CSRF防御机制但是我们这里为了测试方便先将CSRF防御机制关闭在后面将会详细介绍CSRF攻击与防御问题。 配置完成后启动Spring Boot项目,浏览器地址栏中输入http://localhost:8080/index会自动跳转到http://localhost:8080/loginNew.html页面如图2-5所示。输入用户名和密码进行登录(用 户名为buretuzi,密码为123456),登录成功之后就可以访问到index页面了如图2-6所示。 经过上面的配置我们已经成功自定义了一个登录页面出来用户在登录成功之后就可以访问受保护的资源了。 1.2、配置细节 当然前面的配置比较粗糙这里还有一些配置的细节需要和读者分享一下。 在前面的配置中我们用defaultSuccessUrl表示用户登录成功后的跳转地址用failureUrl 表示用户登录失败后的跳转地址。关于登录成功和登录失败除了这两个方法可以配置之外, 还有另外两个方法也可以配置。 1.2.1、登录成功 当用户登录成功之后除了 defaultSuccessUrl方法可以实现登录成功后的跳转之外 successForwardUrl也可以实现登录成功后的跳转代码如下 Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage(/loginNew.html).loginProcessingUrl(/doLogin).successForwardUrl(/index).failureUrl(/loginNew.html).usernameParameter(uname).passwordParameter(passwd).permitAll().and().csrf().disable();}}defaultSuccessUrl 和 successForwardUrl 的区别如下 defaultSuccessUrl表示当用户登录成功之后会自动重定向到登录之前的地址上 如果用户本身就是直接访问的登录页面则登录成功后就会重定向到defaultSuccessUrl指定的页面中。例如用户在未认证的情况下访问了/hello页面此时会自动重定向到登录页面 当用户登录成功后就会自动重定向到/hello页面而用户如果一开始就访问登录页面则登录成功后就会自动重定向到defaultSuccessUrl所指定的页面中.successForwardUrl则不会考虑用户之前的访问地址只要用户登录成功就会通过服务器端跳转到successForwardUrl所指定的页面;defaultSuccessUrl有一个重载方法如果重载方法的第二个参数传入true,则 defaultSuccessUrl的效果与successForwardUrl类似即不考虑用户之前的访问地址只要登录成功,就重定向到defaultSuccessUrl所指定的页面。不同之处在于defaultSuccessUrl是通过重定向实现的跳转(客户端跳转)successForwardUrl则是通过服务器端跳转实现的。 无论是 defaultSuccessUrl 还是 successForwardUrl最终所配置的都是 AuthenticationSuccessHandler接口的实例。 Spring Security中专门提供了 AuthenticationSuccessHandler接口用来处理登录成功事项 public interface AuthenticationSuccessHandler {default void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException{onAuthenticationSuccess(request, response, authentication);chain.doFilter(request, response);}void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException;}由上述代码可以看到AuthenticationSuccessHandler接口中一共定义了两个方法其中一 个是default方法此方法是Spring Security 5.2开始加入进来的在处理特定的认证请求 AuthenticationFilter中会用到另外一个非default方法则用来处理登录成功的具体事项其 中request和response参数好理解authentication参数保存了登录成功的用户信息。我们将在后面的章节中详细介绍authentication参数。 AuthenticationSuccessHandler接口共有三个实现类如图2-7所示。 1 SimpleUrlAuthenticationSuccessHandler继承自 AbstractAuthenticationTargetUrlRequestHandler通过 AbstractAuthenticationTargetUrlRequestHandler 中的 handle 方法实现请求重定向。 2SavedRequestAwareAuthenticationSuccessHandler在 SimpleUrlAuthenticationSuccessHandler的基础上增加了请求缓存的功能可以记录之前请求的地址进而在登录成功后重定向到一开始访问的地址。 3 ForwardAuthenticationSuccessHandler的实现则比较容易就是一个服务端跳转。 我们来重点分析 SavedRequestAwareAuthenticationSuccessHandler和ForwardAuthenticationSuccessHandler的实现。 当通过defaultSuccessUrl来设置登录成功后重定向的地址时实际上对应的实现类就是 SavedRequestAwareAuthenticationSuccessHandler。 public class SavedRequestAwareAuthenticationSuccessHandler extendsSimpleUrlAuthenticationSuccessHandler {protected final Log logger LogFactory.getLog(this.getClass());private RequestCache requestCache new HttpSessionRequestCache();Overridepublic void onAuthenticationSuccess(HttpServletRequest request,HttpServletResponse response, Authentication authentication)throws ServletException, IOException {SavedRequest savedRequest requestCache.getRequest(request, response);if (savedRequest null) {super.onAuthenticationSuccess(request, response, authentication);return;}String targetUrlParameter getTargetUrlParameter();if (isAlwaysUseDefaultTargetUrl()|| (targetUrlParameter ! null StringUtils.hasText(request.getParameter(targetUrlParameter)))) {requestCache.removeRequest(request, response);super.onAuthenticationSuccess(request, response, authentication);return;}clearAuthenticationAttributes(request);// Use the DefaultSavedRequest URLString targetUrl savedRequest.getRedirectUrl();logger.debug(Redirecting to DefaultSavedRequest Url: targetUrl);getRedirectStrategy().sendRedirect(request, response, targetUrl);}public void setRequestCache(RequestCache requestCache) {this.requestCache requestCache;} }这里的核心方法就是onAuthenticationSuccess: 首先从requestcache中获取缓存下来的请求如果没有获取到缓存请求就说明用户在访问登录页面之前并没有访问其他页面此时直接调用父类的onAuthenticationSuccess方法来处理最终会重定向到defaultSuccessUrl指定的地址。接下来会获取一个targetUrlParameter,这个是用户显式指定的、希望登录成功后重定向的地址例如用户发送的登录请求是http://localhost:8080/doLogin?target/hello,这就表示当用户登录成功之后希望自动重定向到/hello这个接口getTargetUrlParameter就是要获取重定向地址参数的key,也就是上面的target,拿到target之后就可以获取到重定向地址了。如果 targetUrlParameter 存在或者用户设置了 alwaysUseDefaultTargetUrl 为 true, 这个时候缓存下来的请求就没有意义了。此时会直接调用父类的onAuthenticationSuccess方法完成重定向口 targetUrlParameter存在则直接重定向到targetUrlParameter指定的地址alwaysUseDefaultTargetUrl 为 true,则直接重定向到 defaultSuccessUrl 指定的地址如果 targetUrlParameter 存在并且 alwaysUseDefaultTargetUrl 为 true,则重定向到 defaultSuccessUrl 指定的地址。如果前面的条件都不满足那么最终会从缓存请求savedRequest中获取重定向地址, 然后进行重定向操作。 这就是SavedRequestAwareAuthenticationSuccessHandler的实现逻辑升发者也可以配置 自己的 SavedRequestAwareAuthenticationSuccessHandler,代码如下 Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage(/loginNew.html).loginProcessingUrl(/doLogin).successForwardUrl(/index).failureUrl(/loginNew.html).usernameParameter(uname).passwordParameter(passwd).permitAll().and().csrf().disable();}SavedRequestAwareAuthenticationSuccessHandler successHandler(){SavedRequestAwareAuthenticationSuccessHandler handler new SavedRequestAwareAuthenticationSuccessHandler();handler.setDefaultTargetUrl(/index);handler.setTargetUrlParameter(target);return handler;}}注意在配置时指定了 targetUrlParameter为target,这样用户就可以在登录请求中通过 target来指定跳转地址了然后我们修改一下前面login.html中的form表单 form idlogin-form classform action/doLogin?target/hello methodposth3 classtext-center text-info登录/h3div classform-grouplabel forusername classtext-info用户名/labelbrinput typetext nameuname idusername classform-control/divdiv classform-grouplabel forpassword classtext-info密码/labelbrinput typetext namepasswd idpassword classform-control/divdiv classform-groupinput typesubmit namesubmit classbtn btn-info btn-md value登录/div /form在form表单中action修改/doLogin?target/hello,这样当用户登录成功之后就始终跳转到/hello接口了。 当我们通过successForwardUrl来设置登录成功后重定向的地址时实际上对应的实现类 就是 ForwardAuthenticationSuccessHandlerForwardAuthenticationSuccessHandler 的源码特别简单就是一个服务端转发代码如下 public class ForwardAuthenticationSuccessHandler implements AuthenticationSuccessHandler {private final String forwardUrl;public ForwardAuthenticationSuccessHandler(String forwardUrl) {Assert.isTrue(UrlUtils.isValidRedirectUrl(forwardUrl),() - forwardUrl is not a valid forward URL);this.forwardUrl forwardUrl;}public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {request.getRequestDispatcher(forwardUrl).forward(request, response);}}由上述代码可以看到主要功能就是调用getRequestDispatcher方法进行服务端转发。 AuthenticationSuccessHandler默认的三个实现类无论是哪一个都是用来处理页面跳转的有时候页面跳转并不能满足我们的需求特别是现在流行的前后端分离开发中用户登录成功后就不再需要页面跳转了只需要给前端返回一个JSON数据即可告诉前端登录成功还是登录失败前端收到消息之后自行处理。像这样的需求我们可以通过自定义 AuthenticationSuccessHandler 的实现类来完成 package com.intehel.demo.handler;import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map;public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)throws IOException, ServletException {response.setContentType(application/json;charsetUTF-8);MapString,Object resp new HashMapString,Object();resp.put(status,200);resp.put(msg,登录成功);ObjectMapper om new ObjectMapper();String s om.writeValueAsString(resp);response.getWriter().write(s);}}在自定义的 MyAuthenticationSuccessHandler中重写 onAuthenticationSuccess方法在该方法中通过HttpServletResponse对象返回一段登录成功的JSON字符串给前端即可。最后 在 SecurityConfig中配置自定义的 MyAuthenticationSuccessHandler代码如下 Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage(/loginNew.html).loginProcessingUrl(/doLogin).successHandler(new MyAuthenticationSuccessHandler()).failureUrl(/loginNew.html).usernameParameter(uname).passwordParameter(passwd).permitAll().and().csrf().disable();}}配置完成后重启项目此时当用户成功登录之后就不会进行页面跳转了而是返回一段JSON字符串: 1.2.2、登录失败 接下来看登录失败的处理逻辑。为了方便在前端页面展示登录失败的异常信息我们首先在项目的pom.xml文件中引入thymeleaf依赖代码如下 dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-thymeleaf/artifactIdversion2.0.7.RELEASE/version /dependency然后在resources/templates目录下新建mylogin.html代码如下 !DOCTYPE html html langen xmlns:thhttp://www.thymeleaf.org headmeta charsetUTF-8title登录/titlelink href//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css relstylesheet idbootstrap-cssscript src//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js/scriptscript src//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js/script /head style#login .container #login-row #login-column #login-box {border: 1px solid #9c9c9c;background-color: #EAEAEA;} /style body div idlogindiv classcontainerdiv idlogin-row classrow justify-content-center align-items-centerdiv idlogin-column classcol-md-6div idlogin-box classcol-md-12form idlogin-form classform action/doLogin?target/hello methodposth3 classtext-center text-info登录/h3div th:text${SPRING SECURITY LAST EXCEPTION}/divdiv classform-grouplabel forusername classtext-info用户名/labelbrinput typetext nameuname idusername classform-control/divdiv classform-grouplabel forpassword classtext-info密码/labelbrinput typetext namepasswd idpassword classform-control/divdiv classform-groupinput typesubmit namesubmit classbtn btn-info btn-md value登录/div/form/div/div/div/div /div /body /htmlmylogin.html和前面的login.html基本类似前面的login.html是静态页面这里的 mylogin.html是thymeleaf模板页面mylogin.html页面在form中多了一个div,用来展示登录失败时候的异常信息登录失败的异常信息会放在request中返回到前端开发者可以将其直接提取岀来展示。 既然mylogm.html是动态页面就不能像静态页面那样直接访问了需要我们给mylogin.html页面提供一个访问控制器 package com.intehel.demo.controller;import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;Controller public class MyLoginController {RequestMapping(/mylogin.html)public String myLogin(){return mylogin;}}最后再在SecurityConfig中配置登录页面代码如下 Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage(/mylogin.html).loginProcessingUrl(/doLogin).defaultSuccessUrl(/index.html).failureUrl(/mylogin.html).usernameParameter(uname).passwordParameter(passwd).permitAll().and().csrf().disable();} }failureUrl表示登录失败后重定向到mylogin.html页面。重定向是一种客户端跳转重定向不方便携带请求失败的异常信息(只能放在URL中)。 如果希望能够在前端展示请求失败的异常信息可以使用下面这种方式 Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage(/mylogin.html).loginProcessingUrl(/doLogin).defaultSuccessUrl(/index.html).failureForwardUrl(/mylogin.html).usernameParameter(uname).passwordParameter(passwd).permitAll().and().csrf().disable();}}failureForwardUrl方法从名字上就可以看出这种跳转是一种服务器端跳转服务器端跳转的好处是可以携带登录异常信息如果登录失败自动跳转回登录页面后就可以将错误信息展示出来如图2-8所示。 无论是 failureUrl 还是 failureForwardUrl,最终所配置的都是 AuthenticationFailureHandler 接口的实现。Spring Security中提供了 AuthenticationFailureHandler 接口用来规范登录失败的 实现 public interface AuthenticationFailureHandler {void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException;}AuthenticationFailureHandler 接口中只有一个 onAuthenticationFailure 方法用来处理登录 失败请求request和response参数很好理解最后的exception则表示登录失败的异常信息。 Spring Security 中为 AuthenticationFailureHandler 一共提供了五个实现类如图 SimpleUrlAuthenticationFailureHandler默认的处理逻辑就是通过重定向跳转到登录页 面当然也可以通过配置forwardToDestination属性将重定向改为服务器端跳转failureUrl方法的底层实现逻辑就是 SimpleUrlAuthenticationFailureHandler。ExceptionMappingAuthenticationFailureHandler可以实现根据不同的异常类型映射到不同的路径。ForwardAuthenticationFailureHandler表示通过服务器端跳转来重新回到登录页面 failureForwardUrl 方法的底层实现逻辑就是 ForwardAuthenticationFailureHandler。AuthenticationEntryPointFailureHandler是 Spring Security 5.2 新引进的处理类可以 通过AuthenticationEntryPoint来处理登录异常。DelegatingAuthenticationFailureHandler可以实现为不同的异常类型配置不同的登录失败处理回调。 这里举一个简单的例子。假如不使用failureForwardUrl 方法同时又想在登录失败后通过服务器端跳转回到登录页面那么可以自定义SimpleUrlAuthenticationFailureHandler配置并将forwardToDestination属性设置为true,代码如下 Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage(/mylogin.html).loginProcessingUrl(/doLogin).defaultSuccessUrl(/index.html).failureHandler(failureHandler()).usernameParameter(uname).passwordParameter(passwd).permitAll().and().csrf().disable();}SimpleUrlAuthenticationFailureHandler failureHandler(){SimpleUrlAuthenticationFailureHandler handler new SimpleUrlAuthenticationFailureHandler(/mylogin.html);handler.setUseForward(true);return handler;}}这样配置之后如果用户再次登录失败就会通过服务端跳转重新回到登录页面登录页而也会展示相应的错误信息效果和failureForwardUrl 一致。 SimpleUrlAuthenticationFailureHandler的源码也很简单我们一起来看一下实现逻辑(源码比较长这里列出来核心部分): public class SimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler {protected final Log logger LogFactory.getLog(getClass());private String defaultFailureUrl;private boolean forwardToDestination false;private boolean allowSessionCreation true;private RedirectStrategy redirectStrategy new DefaultRedirectStrategy();public SimpleUrlAuthenticationFailureHandler() {}public SimpleUrlAuthenticationFailureHandler(String defaultFailureUrl) {setDefaultFailureUrl(defaultFailureUrl);}public void onAuthenticationFailure(HttpServletRequest request,HttpServletResponse response, AuthenticationException exception)throws IOException, ServletException {if (defaultFailureUrl null) {logger.debug(No failure URL set, sending 401 Unauthorized error);response.sendError(HttpStatus.UNAUTHORIZED.value(),HttpStatus.UNAUTHORIZED.getReasonPhrase());} else {saveException(request, exception);if (forwardToDestination) {logger.debug(Forwarding to defaultFailureUrl);request.getRequestDispatcher(defaultFailureUrl).forward(request, response);} else {logger.debug(Redirecting to defaultFailureUrl);redirectStrategy.sendRedirect(request, response, defaultFailureUrl);}}}protected final void saveException(HttpServletRequest request,AuthenticationException exception) {if (forwardToDestination) {request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);} else {HttpSession session request.getSession(false);if (session ! null || allowSessionCreation) {request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION,exception);}}}public void setDefaultFailureUrl(String defaultFailureUrl) {Assert.isTrue(UrlUtils.isValidRedirectUrl(defaultFailureUrl),() - defaultFailureUrl is not a valid redirect URL);this.defaultFailureUrl defaultFailureUrl;}protected boolean isUseForward() {return forwardToDestination;}public void setUseForward(boolean forwardToDestination) {this.forwardToDestination forwardToDestination;}}从这段源码中可以看到当用户构造SimpleUrlAuthenticationFailureHandler对象的时候 就传入了 defaultFailureUrl也就是登录失败时要跳转的地址。在onAuthenticationFailure方法中如果发现defaultFailureUrl为null,则直接通过response返回异常信息否则调用 saveException 方法。在 saveException 方法中如果 fowardToDestination 属性设置为ture表示通过服务器端跳转回到登录页面此时就把异常信息放到request中。再回到 onAuthenticationFailure方法中如果用户设置fowardToDestination 为 true,就通过服务器 端跳转回到登录页面否则通过重定向回到登录页面。 如果是前后端分离开发登录失败时就不需要页面跳转了只需要返回JSON字符串给前端即可此时可以通过自定义AuthenticationFailureHandler的实现类来完成代码如下: package com.intehel.demo.handler;import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map;public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)throws IOException, ServletException {response.setContentType(application/json;charsetUTF-8);MapString,Object resp new HashMapString,Object();resp.put(status,500);resp.put(msg,登录失败exception.getMessage());ObjectMapper om new ObjectMapper();String s om.writeValueAsString(resp);response.getWriter().write(s);}}然后在SecurityConfig中进行配置即可 package com.intehel.demo.config;import com.intehel.demo.handler.MyAuthenticationFailureHandler; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage(/mylogin.html).loginProcessingUrl(/doLogin).defaultSuccessUrl(/index.html).failureHandler(new MyAuthenticationFailureHandler()).usernameParameter(uname).passwordParameter(passwd).permitAll().and().csrf().disable();}}配置完成后当用户再次登录失败就不会进行页而跳转了而是直接返回JSON字符串, 如图2-10所示。 1.2.3、注销登录 Spring Security中提供了默认的注销页面当然开发者也可以根据自己的需求对注销登录进行定制。 Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage(/mylogin.html).loginProcessingUrl(/doLogin).defaultSuccessUrl(/index.html).failureHandler(new MyAuthenticationFailureHandler()).usernameParameter(uname).passwordParameter(passwd).permitAll().and().logout().logoutUrl(/logout).invalidateHttpSession(true).clearAuthentication(true).logoutSuccessUrl(/mylogin.html).and().csrf().disable();}}通过.logout()方法开启注销登录配置。logoutUrl指定了注销登录请求地址默认是GET请求路径为/logout。invalidateHttpSession 表示是否使 session 失效默认为 true。clearAuthentication表示是否清除认证信息默认为true。logoutSuccessUrl表示注销登录后的跳转地址。 配置完成后再次启动项目登录成功后在浏览器中输入http://localhost:8080/logout就可以发起注销登录请求了注销成功后会自动跳转到mylogin.html页面。 如果项目有需要开发者也可以配置多个注销登录的请求同时还可以指定请求的方法。 package com.intehel.demo.config;import com.intehel.demo.handler.MyAuthenticationFailureHandler; 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.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.OrRequestMatcher;Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage(/mylogin.html).loginProcessingUrl(/doLogin).defaultSuccessUrl(/index.html).failureHandler(new MyAuthenticationFailureHandler()).usernameParameter(uname).passwordParameter(passwd).permitAll().and().logout().logoutRequestMatcher(new OrRequestMatcher(new AntPathRequestMatcher(/logout1,GET),new AntPathRequestMatcher(/logout2,POST))).invalidateHttpSession(true).clearAuthentication(true).logoutSuccessUrl(/mylogin.html).and().csrf().disable();}}上面这个配置表示注销请求路径有两个 第一个是/logout1,请求方法是GET。第二个是/logout2,请求方法是POST。 使用任意一个请求都可以完成登录注销。 如果项目是前后端分离的架构注销成功后就不需要页面跳转了只需将注销成功的信息返回给前端即可此时我们可以自定义返回内容 Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage(/mylogin.html).loginProcessingUrl(/doLogin).defaultSuccessUrl(/index.html).failureHandler(new MyAuthenticationFailureHandler()).usernameParameter(uname).passwordParameter(passwd).permitAll().and().logout().logoutRequestMatcher(new OrRequestMatcher(new AntPathRequestMatcher(/logout1,GET),new AntPathRequestMatcher(/logout2,POST))).invalidateHttpSession(true).clearAuthentication(true).logoutSuccessHandler((req,resp,auth)-{resp.setContentType(application/json;charsetUTF-8);MapString,Object result new HashMapString,Object();result.put(status,200);result.put(msg,注销成功);ObjectMapper om new ObjectMapper();String s om.writeValueAsString(result);resp.getWriter().write(s);}).and().csrf().disable();}}配置 logoutSuccessHandler 和 logoutSuccessUrl 类似于前面所介绍的 successHandler 和defaultSuccessUrl之间的关系只是类不同而已因此这里不再赘述读者可以按照我们前面的分析思路自行分析。 配置完成后重启项目登录成功后再去注销登录无论是使用/logout1还是/logout2进行注销只要注销成功后就会返回一段JSON字符串。 如果开发者希望为不同的注销地址返回不同的结果也是可以的配置如下 Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage(/mylogin.html).loginProcessingUrl(/doLogin).defaultSuccessUrl(/index.html).failureHandler(new MyAuthenticationFailureHandler()).usernameParameter(uname).passwordParameter(passwd).permitAll().and().logout().logoutRequestMatcher(new OrRequestMatcher(new AntPathRequestMatcher(/logout1,GET),new AntPathRequestMatcher(/logout2,POST))).invalidateHttpSession(true).clearAuthentication(true).defaultLogoutSuccessHandlerFor((req,resp,auth)-{resp.setContentType(application/json;charsetUTF-8);MapString,Object result new HashMapString,Object();result.put(status,200);result.put(msg,使用logout1注销成功);ObjectMapper om new ObjectMapper();String s om.writeValueAsString(result);resp.getWriter().write(s);},new AntPathRequestMatcher(/logout1,GET)).defaultLogoutSuccessHandlerFor((req,resp,auth)-{resp.setContentType(application/json;charsetUTF-8);MapString,Object result new HashMapString,Object();result.put(status,200);result.put(msg,使用logout2注销成功);ObjectMapper om new ObjectMapper();String s om.writeValueAsString(result);resp.getWriter().write(s);},new AntPathRequestMatcher(/logout1,GET)).and().csrf().disable();}}通过defaultLogoutSuccessHandlerFor方法可以注册多个不同的注销成功回调函数该方法第一个参数是注销成功回调第二个参数则是具体的注销请求。当用户注销成功后使用了哪个注销请求就给出对应的响应信息。
http://www.dnsts.com.cn/news/280208.html

相关文章:

  • 网络营销的方法seo服务公司深圳
  • 建筑模型网站有哪些小男生和大人做的网站
  • 广东深广东深圳网站建设服务山西建设厅网站
  • 商务网站建设的应用it外包中心
  • 提供网站建设收益分录建设银行公积金预约网站
  • 长沙公司网站设计报价整合网络营销
  • 流媒体网站建设规划腾讯云如何注册域名
  • 想在网上做设计接单有没有网站万户做的网站安全吗
  • 网站的排版问题广州公司注册名称核名查询系统网页版
  • 福建省城乡住房建设厅网站wordpress 双模式
  • 百度权重查询入口福州seo公司网站
  • sns网站建设哪家公司好昆明企业网站建设一条龙
  • wordpress文字头像网站营销优化方案
  • wordpress怎么加快网站打开速度江西省建设厅官方网站
  • 西安商城网站建设vi设计是设计什么东西
  • 我做的网站服务器别人没法左键点击下载呢济南做网站建网站公司
  • 建设一个网站的好处柳州旅游网站建设
  • 怎么在百度做原创视频网站网站推广建站
  • 网站建设制作设计seo优化珠海在哪里找工厂采购信息
  • 域名注册网站搭建wordpress文件储存
  • 腾讯网站建设推广海兴做网站价格
  • 西部数码 网站管理合肥市城乡建设局
  • 苏州企业建站公司做58同城网站花了多少钱
  • 郑州百度seo网站优化怎么免费制作网页
  • 十条网站建设的seo策略东莞做网站 信科网络
  • 淘客网站开发教程网站的后台系统怎么进入
  • 石家庄网站建设优化泰兴网站建设吧
  • 融安有那几个网站做的比较好的莆田网站制作价格
  • 网站备案个人和企业的区别陕西省建设网官网
  • 织梦网站地图在线生成招聘网站的简历可以做几份