如何使用Spring Boot和Spring Security保护REST API?

如何使用Spring Boot和Spring Security保护REST API?,第1张

如何使用Spring Boot和Spring Security保护REST API?

基于令牌的身份验证-用户将提供其凭据,并获得唯一且受时间限制的访问令牌。我想在自己的实现中管理令牌的创建,检查有效性和到期时间。

实际上,将过滤器用于令牌验证-这种情况下的最佳方法

最终,你可以通过Spring Data创建CRUD,以管理Token的属性(例如过期)等。

和令牌服务实施

http://pastebin.com/dUYM555E

某些REST资源将是公共的-完全不需要身份验证

没问题,你可以通过Spring安全配置来管理资源,如下所示:

.antMatchers("/rest/blabla/**").permitAll()

某些资源仅对具有管理员权限的用户可用,

看一下

@Secured
注解类。例:

@Controller@RequestMapping(value = "/adminservice")@Secured("ROLE_ADMIN")public class AdminServiceController {

授权所有用户后,即可访问其他资源。

回到Spring Security configure,你可以像这样配置URL:

    http .authorizeRequests() .antMatchers("/openforall/**").permitAll() .antMatchers("/alsoopen/**").permitAll() .anyRequest().authenticated()

我不想使用基本身份验证

是的,通过令牌过滤器,你的用户将通过身份验证。

Java代码配置(非XML)

回到上面的话,看

@EnableWebSecurity
。你的课程将是:

@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {}

你必须重写configure方法。下面的代码仅作为示例,介绍如何配置匹配器。它来自另一个项目。

    @Overrideprotected void configure(HttpSecurity http) throws Exception {    http .authorizeRequests() .antMatchers("/assets/**").permitAll() .anyRequest().authenticated() .and() .formLogin()     .usernameParameter("j_username")     .passwordParameter("j_password")     .loginPage("/login")     .defaultSuccessUrl("/", true)     .successHandler(customAuthenticationSuccessHandler)     .permitAll() .and()     .logout()     .logoutUrl("/logout")     .invalidateHttpSession(true)     .logoutSuccessUrl("/")     .deletecookies("JSESSIONID")     .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .and()     .csrf();}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5014363.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-14
下一篇2022-11-14

发表评论

登录后才能评论

评论列表(0条)

    保存