Restful风格服务端应用的Spring Boot + Spring Security配置

         参考http://blog.csdn.net/suhale/article/details/44969221的文档,通过自己的代码来实现了Spring Boot + Spring Security的Restful格式返回参数。

        采用了Maven的方式获取最新版本的Spring Boot,配置如下:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
</dependencies>

 配置完成后,我们首先定义三层结构及dao,service,controller,数据库使用的是mysql,dao框架是mybatis,在这里我们主要看UserServiceImpl的定义,因为UserServiceImpl实现了springframerk.security框架的UserDetailsService,所以我们这里重写了loadUserByUsername的方法,这里重写的目的是为了按照自己的数据库获取用户信息,代码如下:

@Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        UserInfo userInfo = getUserByName(userName);
        if (userInfo == null) {
            throw new UsernameNotFoundException(userName);
        }

        //根据用户获取用户角色
        List<Role> roles = roleService.getUserRole(userInfo.getUserId());
        //定义权限集合
        List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<SimpleGrantedAuthority>();
        //添加权限到集合中
        for (Role role : roles){
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleType()));
        }
        boolean booleanStatus = true;
        if(userInfo.getStatus() == 0){
            booleanStatus = false;
        }
        //加密密码
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(16);
        User user = new User(userInfo.getUserName(),bCryptPasswordEncoder.encode(userInfo.getPassword()),booleanStatus,true,true, true, grantedAuthorities);
        return user;
    }

 这里的加密密码是因为我的数据库的密码字段是手工随便输入的可读密码。

 

          接着我们定义一个WebSecurityConfig类继承WebSecurityConfigurerAdapter类,用于实现访问权限的配置,部分代码如下:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        //禁用CSRF保护
        .csrf().disable()
        .authorizeRequests()
        //任何访问都必须授权
        .anyRequest().fullyAuthenticated()
        //配置那些路径可以不用权限访问
        .mvcMatchers("/login").permitAll()
        .and()
        .formLogin()
        //登陆成功后的处理,因为是API的形式所以不用跳转页面
        .successHandler(new RestAuthenticationSuccessHandler())
        //登陆失败后的处理
        .failureHandler(new SimpleUrlAuthenticationFailureHandler())
        .and()
        //登出后的处理
        .logout().logoutSuccessHandler(new RestLogoutSuccessHandler())
        .and()
        //认证不通过后的处理
        .exceptionHandling()
        .authenticationEntryPoint(new RestAuthenticationEntryPoint())
        ;
    }

       最后我们可以通过定义controller的方式进行方法的访问,部分代码如下:

 

@RequestMapping(value = "/getUserInfo",method = RequestMethod.GET)
    @PreAuthorize("hasRole('USER')")
    public UserInfo getUserInfo(UserInfo user){
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName("LIQIN");
        userInfo.setPassword("123");
        return userInfo;
    }


@RequestMapping(value = "/getAuth",method = RequestMethod.GET)
    @PreAuthorize("hasRole('ADMIN')")
    public UserInfo getAuth(UserInfo user){
        UserInfo userInfo = new UserInfo();
        //userInfo.setUserName("LIQIN");
        userInfo.setPassword("123");
        return userInfo;
    }

       我使用的开发工具是Idea,代码启动后使用自带的restful工具测试如下:

 

没有登陆的时候:

 

 

          使用/login登陆的时候只输入用户名,没有输入密码:



 将会出现如下错误:



 登陆成功后,就可以进行方法的访问了:



 最后我的代码及数据库的设置在附件里,或者访问我的git可以下载:

https://github.com/422518490/Spring-Security-

更多关于Spring Security的介绍请参考官方文档http://docs.spring.io/spring-security/site/docs/4.2.0.BUILD-SNAPSHOT/reference/htmlsingle/#crypto

猜你喜欢

转载自357029540.iteye.com/blog/2329730