SpringSecurity(一)自定义登录界面

1. 新建一个SpringBoot工程

添加如下依赖

        
            org.springframework.boot
            spring-boot-starter-security
        

        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        

2. 新建LoginController,设置登录页面的路由。

@Controller
public class LoginController {

    @GetMapping("/authentication/login")
    public String authenticationLogin() throws IOException {
        return "login";
    }
}

login页面的html代码如下




    登录
    
    
    
    
    
    


登陆

3.  新建SpringSecurityConfig

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/authentication/*","/login") // 不需要登录就可以访问
                .permitAll()
                .antMatchers("/user/**").hasAnyRole("USER") // 需要具有ROLE_USER角色才能访问
                .antMatchers("/admin/**").hasAnyRole("ADMIN") // 需要具有ROLE_ADMIN角色才能访问
                .anyRequest().authenticated()
                .and()
                    .formLogin()
                    .loginPage("/authentication/login") // 设置登录页面
                    .loginProcessingUrl("/authentication/form")
                    .defaultSuccessUrl("/user/index") // 设置默认登录成功后跳转的页面
                ;
    }

    // 密码加密方式
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    // 重写方法,自定义用户
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("lzc").password(new BCryptPasswordEncoder().encode("123456")).roles("ADMIN","USER");
        auth.inMemoryAuthentication().withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("USER");
    }
}

4. 测试。

访问/user/index,将会跳转到如下页面

SpringSecurity(一)自定义登录界面_第1张图片

输入正确的账号和密码

SpringSecurity(一)自定义登录界面_第2张图片

而实际应用中,用户的账号和密码肯定不是写死在程序中的,下一篇将会介绍如何从数据库中获取用户进行登录。

代码地址  : https://github.com/923226145/SpringSecurity/tree/master/chapter1

 

 

 

你可能感兴趣的:(SpringBoot,SpringSecurity)