码迷,mamicode.com
首页 > 编程语言 > 详细

JSP中使用SpringBoot Security步骤

时间:2016-05-12 15:48:00      阅读:1145      评论:0      收藏:0      [点我收藏+]

标签:

  1. 引入POM文件
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.3.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.1.0</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>springboot-web-jsp</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

2.创建角色和用户表

1@Entity
@Table(name="SYS_ROLES")
public class SysRole extends BaseEntity{


    private static final long serialVersionUID = 5799265763294090239L;
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
(2):**用户表需要实现UserDetails接口,重写getAuthorities()方法**
@Entity()
@Table(name="SYS_USERS")
public class SysUser extends BaseEntity implements UserDetails{

    private static final long serialVersionUID = 2060489721205695393L;

    private String username;

    private String password;

    @ManyToMany(cascade={CascadeType.REFRESH},fetch=FetchType.EAGER)
    private List<SysRole> roles;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities=new ArrayList<GrantedAuthority>();
        List<SysRole> sysRoles=this.getRoles();
        for (SysRole sysRole : sysRoles) {
            authorities.add(new SimpleGrantedAuthority(sysRole.getName()));
        }
        return authorities;
    }
}

3.编写Repository,Service类

1):我是使用的JPA来实现数据访问,此处根据你项目需要来选择需要的Repository接口
public interface SysUserRepository extends JpaRepository<SysUser, String>{

    SysUser findByUsername(String name);
}
(2):**service需要实现UserDetailsService接口,重写loadUserByUsername方法,引入需要的Repository来访问数据库**
@Service
public class SysUserService implements UserDetailsService{

    @Autowired
    SysUserRepository sysUserRepository;

    @Override
    public UserDetails loadUserByUsername(String name)
            throws UsernameNotFoundException {
        SysUser sysUser=sysUserRepository.findByUsername(name);
        if(sysUser==null){
            throw new UsernameNotFoundException("该用户不存在!");
        }
        return sysUser;
    }

}

4.写SecurityConfig配置文件

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    UserDetailsService sysUserService() {
        return new SysUserService();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/static/**");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //此处我把csrf校验取消,开始总是报错,就是它惹的祸
        http.csrf().disable().authorizeRequests()
                        .anyRequest().authenticated() //任何用户需要权限校验
                        .and()
                        .formLogin()
                        .loginPage("/login")
                        .failureUrl("/login?error")
                        .permitAll() 
                        .and()
                        .logout().permitAll(); 


    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //校验注入Service
        auth.userDetailsService(sysUserService());
    }
}

5.在JSP页面引入spring security标签

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

    ROLE_ADMIN,ROLE_HR,ROLE_COMMON这些角色在sys_roles表中设置
            <sec:authorize access="hasRole(‘ROLE_ADMIN‘)">
                <div>
                    <!-- 3 -->
                    <p class="bg-info">${msg.content_admin}</p>
                </div>
            </sec:authorize>
            <sec:authorize access="hasRole(‘ROLE_HR‘)">
                <div>
                    <!-- 3 -->
                    <p class="bg-info">只有HR角色的人员才能看到</p>
                </div>
            </sec:authorize>

            <sec:authorize access="hasRole(‘ROLE_COMMON‘)">
                <div>
                    <p class="bg-info">所以用户都能看到</p>
                </div>
            </sec:authorize>

JSP中使用SpringBoot Security步骤

标签:

原文地址:http://blog.csdn.net/dyd_love/article/details/51364847

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!