JAVA学习之Spring Security

1、创建sprogboot项目,注入依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2、启动项目之后,控制台会打印密码(由于我们没有自定义用户名和密码,所以框架会生成UUID的默认密码。默认用户名为user),然后请求项目任何一个地址,都会跳转默认的登录页login(这也是框架自己支持的)

3、怎么自定义用户名/密码

第一种方式就是在配置文件中增加对应配置:
spring.security.user.name=test
spring.security.user.password=11111111
第二种方式就是在配置类中配置,代码如下:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 设置密码加密
     * @return 返回加密后的密码
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    /**
     * 认证配置
     * @param auth 认证
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // 在内存中配置账户和密码
        auth.inMemoryAuthentication()
                .withUser("lingdong")
                .password("22222222")
                .roles("admin");
    }
}
其中,在配置类中配置的属性优先级会高于配置文件

4、怎么自定义登录页(框架自己支持的登录页太简单),也可以理解为怎么开放登录页面和登录接口

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/district/getDistrictInfoById?id=87875989476085760")
            .permitAll()
            .and()
            .csrf()
            .disable();
}

上述配置也是在SecurityConfig配置类中配置,这段配置代表开放“/district/getDistrictInfoById?id=87875989476085760”这个接口,经测试,任何请求都会转发到这个接口

5、怎么配置不拦截静态资源

/**
* 取消静态拦截
* @param web
* @throws Exception
*/
@Override
public void configure(WebSecurity web) throws Exception {
    // 忽略某些路径
    web.ignoring().antMatchers("/css/**", "/js/**", "/images/**");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值