Security详解—自定义登录页面(3)

        对于Security认证有两种方式一种是表单方式,一种是HttpBasic认证方式。Spring security 5.x以下默认是HttpBasic认证,以上默认是表单认证。表单认证可以使用formLogin()进行配置。

        formLogin默认使用UsernamePasswordAuthenticationFilter过滤器,ProviderManager认证管理,DaoAuthenticationProvider。

        这里使用springboot工程进行开发。

1.新建一个登录页面

        新建一个登录页面并且将登录页面放置到resources目录下的static目录中。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登陆</title>
</head>
<style>
    .form-control {
        height: 25px;
    }
    label{
        font-size: 20px;
    }


    label.username-calss {
        font-weight: bold
    }

</style>
<body>
<div style="text-align: center;">
    <form id="login-form" class="form" action="/doLogin" method="post">
        <h3>登录</h3>
        <label for="username" class="text-into username-calss">用户名</label><br>
        <input type="text" name="uname" id="username" class="form-control"><br>
        <label for="password" class="text-info">密码</label><br>
        <input type="password" name="passwd" id="password" class="form-control"><br>
        <input type="submit" name="submit" class="btn btn-info btn-md" value="登录">
    </form>
</div>
</body>
</html>

2.自定义配置

        新建一个配置类WebSecurityConfig,并且继承WebSecurityConfigurerAdapter(如果WebSecurityConfigurerAdapter。

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService myUserDetailsService;


    /**
     * formLogin() 默认使用了UsernamePasswordAuthenticationFilter
     * 默认使用了DaoAuthenticationProvider认证逻辑,使用configure可以配置UserDetailsService
     *
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //忽略hellopost接口
        http.csrf().disable();

        http.authorizeRequests()
                .antMatchers("/hello", "/loginalert", "/mylogin").permitAll()
                .antMatchers("/helloadmin").hasRole("admin")
                .antMatchers("/hellouser").hasAuthority("query")
                .anyRequest().authenticated()
                .and().formLogin().loginPage("/mylogin.html")
                .usernameParameter("uname").passwordParameter("passwd")
                .permitAll()
                .loginProcessingUrl("/doLogin")
                //登录失败处理
                .failureHandler((request, response, exception) -> {
                    String message = "login fail:" + exception.getMessage();
                    response.setContentType("text/html");
                    response.getWriter().write("<script>alert('" + message + "');window.location.href='/mylogin.html'</script>");
                    //登录成功处理
                }).successHandler(((request, response, authentication) -> {
                    String message = "login success:" + authentication.getName();
                    response.setContentType("text/html");
                    response.getWriter().write("<script>alert('" + message + "');window.location.href='/index'</script>");
                }));

        //权限失败
        http.exceptionHandling().accessDeniedHandler(((request, response, accessDeniedException) -> {
            String message = "access fail:" + accessDeniedException.getMessage();
            response.setContentType("text/html");
            response.getWriter().write("<script>alert('" + message + "');window.location.href='/index'</script>");
        }));
    }


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);
    }
}

配置类

@Configuration
public class MyConfig {


    @Bean
    PasswordEncoder bcryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    UserDetailsService myUserDetailsService() {
        return new MyUserDetailsService();
    }
}

 

如果提示WebSecurityConfigurerAdapter过期,可以使用SecurityFilterChain进行配置。

    @Bean
    SecurityFilterChain managementSecurityFilterChain(HttpSecurity http) throws Exception {
        return http.authorizeRequests()
                .antMatchers("/hello2").permitAll()
                .anyRequest().authenticated()
                .and().formLogin()
                .and()
                .build();
    }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值