08-oauth2-AuthorizationServer-03

2020-06-29  本文已影响0人  16325

搭建认证服务器

WebSecurityConfig

认证服务器,管理token,发放认证token等功能。但是首先他是一个认证服务器,认证,说白了就是需要用户名和密码,判断用户身份,校验用户权限。这部分是spring-security的职责,可以当成是一个纯纯的security应用,按原有套路配置即可。

配置如下:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled=true,jsr250Enabled=true)
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().antMatchers("/actuator/**").permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable()
                .formLogin()
        ;
    }
    /**
     * 授权验证服务
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication().passwordEncoder(passwordEncoder())
                .withUser("simm").password(passwordEncoder().encode("123")).roles("USER").and()
                .withUser("admin").password(passwordEncoder().encode("admin")).roles("USER","ADMIN");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
@RestController
public class EndPoint {



        @RequestMapping("/hello")
        @RolesAllowed("ROLE_ADMIN")  // JSR-250
        @Secured({"ROLE_ADMIN"})   //securedEnabled
        public String hello() {
            SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream().forEach(x-> System.out.println(((GrantedAuthority) x).getAuthority()));
            return "asd";
        }
        @RequestMapping("/changePassword")
        @PreAuthorize("hasRole('ROLE_ADMIN')")
        public String changePassword(long userId ){
            return "hello2";
        }
}

AuthorizationServerConfig

下面来配置认证服务器
注意:

上一篇 下一篇

猜你喜欢

热点阅读