关于安全:Spring-Cloud-Spring-Security实践三-数据库方式的认证和授权

4次阅读

共计 910 个字符,预计需要花费 3 分钟才能阅读完成。

首先,创立针对三种 role 的 controller(App/Admin/User):

@RestController
@RequestMapping("/app/api")
public class Controllers {@GetMapping("hello")
    public String hello(){return "hello, app";}
}
@RestController
@RequestMapping("/admin/api")
class AdminController {@GetMapping("hello")
    public String hello(){return "hello, admin";}
}
@RestController
@RequestMapping("/user/api")
class UserController {@GetMapping("hello")
    public String hello(){return "hello, user";}
}

此三个 controller 别离对应三种 Role,此时咱们在配置中增加权限管制的配置:

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
     @Override
     protected void configure(HttpSecurity http) throws Exception {http.authorizeRequests()
                    .antMatchers("/admin/**").hasRole("ADMIN")
                    .antMatchers("/user/**").hasRole("USER")
                    .antMatchers("/app/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .formLogin();}
}

留神其中的 antMatchers 办法,此办法为采纳ANT 模式的 URL 匹配器

此时重启服务,发现登录后拜访 user 及 admin 资源均提醒 403 谬误,但 app 能够失常进入,阐明此配置没有问题。只短少用户信息的 Role 局部。

正文完
 0