SpringBoot整合Spring Security,使用formLogin模式进行鉴权(二)

一、使用formLogin模式进行鉴权

在configure(HttpSecurity http)方法里写入如下代码

http.csrf().disable()
                .formLogin()
                .loginPage("/login.html")//设置登录页,该页面放在public目录下
                .loginProcessingUrl("/login")//设置登录请求地址,默认就是login
                .defaultSuccessUrl("/index")//设置登录成功后跳转地址
                .usernameParameter("uname")//配置用户名参数,默认是username
                .passwordParameter("pword")//配置密码参数,默认是password
                .and()
                .authorizeRequests()
                .antMatchers("/login.html","/login").permitAll()//配置无需认证即可访问的请求
                .antMatchers("/biz1","/biz2").hasAnyAuthority("ROLE_user","ROLE_admin")//配置需要权限才能访问的请求
                .antMatchers("/syslog","/sysuser").hasAnyAuthority("ROLE_admin")
                .anyRequest().authenticated();//配置其他的所有请求需要认证

然后重写另外两个configure方法

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //从内存里获取用户数据
        auth.inMemoryAuthentication()
                //配置用户信息
                .withUser("user").authorities("ROLE_user").password(new BCryptPasswordEncoder().encode("1"))
                .and()
                //配置管理员信息
                .withUser("admin").authorities("ROLE_user","ROLE_admin").password(new BCryptPasswordEncoder().encode("1"))
                .and()
                //密码均采用BCrypt加密方式
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //放行所有静态资源
        web.ignoring()
                .antMatchers("/css/**","/font/**","/js/**","/img/**");
    }

自定义表单代码:

<form action="/login" method="post">
    <span>用户名称</span><input type="text" name="uname" id="username"/> <br>
    <span>用户密码</span><input type="password" name="pword" id="password"/> <br>
    <span>验证码</span><input type="text" name="captchaCode" id="captchaCode"/>
    <input type="submit" value="登陆">
    <label><input type="checkbox" name="remember-me" id="remember-me"/>记住密码</label>
</form>

记住我功能在configure(HttpSecurity http)方法里加入:

        //开启记住我功能,默认参数是remember-me
        http.rememberMe();

勾选记住我登录成功后,就会有一个remember-me的cookie

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值