其他分享
首页 > 其他分享> > spring security 基于角色的控制,可运行。

spring security 基于角色的控制,可运行。

作者:互联网

基于角色的访问控制

建表语句,见 上一篇 的博文,  https://www.cnblogs.com/sdgtxuyong/p/16157870.html

 

用户 user 继承自 UserDetails

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("sys_user")
public class User  implements UserDetails {

@TableField(exist = false)
private List<Role> roles;

private static final long serialVersionUID = 1L;

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles;
}

 

角色继承自 GrantedAuthority ,这个词,在springsecurity中,代表角色

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("sys_role")
public class Role implements GrantedAuthority {

@Override
public String getAuthority() {
return roleName;
}

@TableField(exist = false)
private List<Permission> permissionList;

 

dao

userdao中,返回值 封装 roles 类型

@Repository
@Transactional
public interface UserDao extends BaseMapper<User> {


    @Select("select * from sys_user where username = #{username}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roles", column = "id", javaType = List.class,
                    many = @Many(select = "cn.taotao.dao.RoleDao.findByUid"))
    })
    public User findByName(String username);

    @Select("select * from sys_user where id=#{id}")
    @Results({
            @Result(id=true, column = "id",property = "id"),
            @Result(column = "username",property = "username"),
            @Result(column = "password",property = "password"),
            @Result(javaType = List.class,property = "roles",column = "id",
                    many=@Many(select="cn.taotao.dao.RoleDao.findRoleById"))
    })
    User findUserAndRoleById(int id);


}

 

roleDao

@Repository
@Transactional
public interface RoleDao extends BaseMapper<Role> {

    @Select("SELECT r.id, r.role_name roleName, r.role_desc roleDesc " +
            "FROM sys_role r, sys_user_role ur " +
            "WHERE r.id=ur.rid AND ur.uid=#{uid}")
    public List<Role> findByUid(Integer uid);

    @Select("SELECT * FROM sys_role r ,sys_user_role ur WHERE r.`ID`=ur.`RID`AND ur.`UID`=#{id}" )
    @Results({
            @Result(id = true, property = "id",column = "id"),
            @Result(property = "roleName",column = "role_name"),
            @Result(property = "roleDesc",column = "role_desc"),
            @Result(property = "permissionList",column = "rid",many = @Many(select="cn.taotao.dao.PermissionDao.findPermissionAndRoleById"))
    })
    List<Role> findRoleById(int id);
}

 

permissionDao

@Repository
@Transactional
public interface PermissionDao extends BaseMapper<Permission> {



    @Select("SELECT * FROM sys_permission p ,sys_role_permission rp WHERE p.`ID`=rp.`PID` AND rp.`RID`=#{id}")
    public List<Permission> findPermissionAndRoleById(int id);
}

 

 

服务层

public interface UserService extends IService<User> , UserDetailsService {
}
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, cn.taotao.domain.User> implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//        cn.taotao.domain.User user = userDao.findByName(s);
//       这些注释掉的,都不需要
//        //根据用户的id查询用户的权限
//       // List<String> permissions = userDao.findPermissionsByUserId(user.getId());
//        cn.taotao.domain.User userAndRoleById = userDao.findUserAndRoleById(user.getId());
//        List<String> permissionLists = new ArrayList<>();
//        userAndRoleById.getRoles().forEach(o->o.getPermissionList().forEach(e->{permissionLists.add(e.getPermissionName());}));
//        //将permissions转成数组
//        String[] permissionArray = new String[permissionLists.size()];
//        permissionLists.toArray(permissionArray);
//        permissionLists.forEach(o-> System.out.println(o));
//        System.err.println("permissionArray = " + permissionArray.toString());
//        UserDetails userDetails = User.withUsername(user.getUsername()).password(user.getPassword()).authorities(permissionArray).build();
//        System.err.println("userDetails = " + userDetails);
        return userDao.findByName(s);

    }

 

异常处理

@ControllerAdvice
public class HandlerControllerException {

    @ExceptionHandler(RuntimeException.class)
    public String handException(RuntimeException e){
        if(e instanceof AccessDeniedException){
            return "redirect:/403.jsp";
        }
        return "redirect:/500.jsp";
    }
}

 

配置类

Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)    // 这里有3个类型可选,用来区分安全级别,有spring的,有springmvc的,有jsr250的,如果这里启用哪个,在控制器中,就必须用那个,来控制权限。
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //指定认证对象的来源
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
    //SpringSecurity配置信息
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login.jsp", "failer.jsp","403.jsp","500.jsp", "/number.jpg","/static/**","/css/**", "/img/**", "/plugins/**").permitAll()
              //  .antMatchers("/add").hasAnyRole("admin")
                .anyRequest().authenticated()
             //   .anyRequest().permitAll()
                .and()
                .formLogin()
                .loginPage("/login.jsp")
                .loginProcessingUrl("/login")
                .successForwardUrl("/index.jsp")
                .failureForwardUrl("/failer.jsp")
                .and()
                .logout()
                .logoutSuccessUrl("/logout")
                .invalidateHttpSession(true)
                .logoutSuccessUrl("/login.jsp")
                .and()
                .csrf()
                .disable()
                .rememberMe()
                .tokenRepository(getPersistentTokenRepository())
                .tokenValiditySeconds(3600)
                .userDetailsService(userDetailsService);
    }

    @Autowired
    private DataSource dataSource;

    //记住我后的登录页面
    @Autowired
    private UserDetailsService userDetailsService;
    //记住我的功能
    @Bean
    public PersistentTokenRepository getPersistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepositoryImpl=new JdbcTokenRepositoryImpl();
        jdbcTokenRepositoryImpl.setDataSource(dataSource);
        //启动时创建一张表,这个参数到第二次启动时必须注释掉,因为已经创建了一张表
//      jdbcTokenRepositoryImpl.setCreateTableOnStartup(true);
        return jdbcTokenRepositoryImpl;
    }

}

 

控制器

    @RequestMapping("/updateOrder/{id}")
   // @PreAuthorize("hasAuthority('updateOrder')")
    @Secured("ROLE_ADMIN")
    public  ModelAndView updateOrder(@PathVariable("id") Long id,@RequestParam("comment") String comment){
        ModelAndView mv = new ModelAndView();

        this.ordersService.update(this.ordersService.getById(id), new UpdateWrapper<Orders>().eq("id",id).set("comment",comment));


        mv.setViewName("redirect:/list");
        return mv;

    }

 

jsp页面

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

<sec:authorize access="hasAnyRole('ROLE_ADMIN')"> <button type="submit" class="btn btn-primary" style="margin-top: 30px">修改备注</button></sec:authorize>

 

标签:角色,column,spring,public,jsp,user,security,id,Result
来源: https://www.cnblogs.com/sdgtxuyong/p/16480675.html