Spring Security实现案例

Spring Security是一个功能强大的安全框架,可以用于保护Web应用程序。下面是一个简单的Spring Security实现案例:

  1. 创建一个Spring Boot项目。

  2. 添加Spring Security依赖。


    org.springframework.security
    spring-security-web
    5.2.2.RELEASE



    org.springframework.security
    spring-security-config
    5.2.2.RELEASE

  1. 创建一个WebSecurityConfigurerAdapter。
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/home")
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/")
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
}
  1. 创建一个UserDetailsService。
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (!"admin".equals(username)) {
            throw new UsernameNotFoundException("Invalid username or password.");
        }
        return new User("admin", "$2a$10$K7RvI2cZuVJZT8Tq3VdZ3OJyXs7Jf8G0YR7vAMGx0J4z4H8tCZ0tS", new ArrayList<>());
    }
}
  1. 创建一个AdminController。
@Controller
@RequestMapping("/admin")
public class AdminController {

    @GetMapping("/")
    public String index() {
        return "admin/index";
    }
}
  1. 创建一个HomeController。
@Controller
public class HomeController {

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @GetMapping("/home")
    public String home() {
        return "home";
    }
}
  1. 创建一个登录页面login.html。



    
    Login


    

Login

  1. 创建一个首页index.html。



    
    Index


    

Index

Welcome to the home page of the Spring Security demo application!

  1. 创建一个管理页面admin/index.html。



    
    Admin


    

Admin

Welcome to the admin page of the Spring Security demo application!

  1. 创建一个成功页面home.html。



    
    Home


    

Home

You have successfully logged in!

  1. 运行应用程序并访问http://localhost:8080/。

  2. 输入用户名admin和密码admin登录。

  3. 访问http://localhost:8080/home和http://localhost:8080/admin/,由于没有相应的角色,将无法访问。

这个案例演示了如何使用Spring Security保护Web应用程序。Spring Security提供了很多的安全特性,如身份验证、授权、加密等,可以保护应用程序免受攻击。

你可能感兴趣的:(spring,java,spring,boot)