spring boot+spring security

pom.xml

<!-- Spring Boot 启动父依赖 -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</parent>
<!-- security -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

contorller

@Controller
public class LoginController
{

    @RequestMapping("/login")
    public String login()
    {
        return "login";
    }

}

service.impl

package org.spring.springboot.service.impl;


import org.spring.springboot.dao.SysUserDao;
import org.spring.springboot.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class CustomUserService implements UserDetailsService
{
    private final String USERNAME_NOT_FOUND = "用户名不存在";

    @Autowired
    SysUserDao sysUserDao;

    @Override
    public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException
    {
        SysUser user = sysUserDao.findByUsername(username);
        if (user == null)
        {
            new UsernameNotFoundException(this.USERNAME_NOT_FOUND);
        }
        return user;
    }

}

config

package org.spring.springboot.config;


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter
{
    @Override
    public void addViewControllers(ViewControllerRegistry registry)
    {
        registry.addViewController("/error").setViewName("login");
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/test/test1").setViewName("/test/test1");
        registry.addViewController("/test/test2").setViewName("/test/test2");
        registry.addViewController("/test/test3").setViewName("/test/test3");
    }
}
package org.spring.springboot.config;


import org.spring.springboot.filter.ValidateCodeFilter;
import org.spring.springboot.service.impl.CustomUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@Configuration
@EnableWebSecurity // 开启Security
@EnableGlobalMethodSecurity(prePostEnabled = true) // AOP
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{

    @Bean
    UserDetailsService customUserService()
    {
        return new CustomUserService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
        throws Exception
    {
        /*BCryptPasswordEncoder encoder =new BCryptPasswordEncoder();
        System.out.println(encoder.encode("123456"));*/
        //对密码进行加密
        auth.userDetailsService(customUserService()).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http)
        throws Exception
    {
        http.authorizeRequests()
                        .antMatchers("/defaultKaptcha")
                        .permitAll()
                        .antMatchers("/**")
                        .authenticated()
                    .and()
                        .formLogin()
                        .loginPage("/login")
                        .permitAll()
                        .defaultSuccessUrl("/index", true)
                    .and()
                        .logout()
                        .logoutUrl("/logout")
                        .logoutSuccessUrl("/login");
        //http.csrf().disable();禁用csrf后可以通过get请求来注销登录
    }

}

dao

package org.spring.springboot.dao;


import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.ResultType;
import org.apache.ibatis.annotations.Select;
import org.spring.springboot.domain.SysUser;


public interface SysUserDao
{
    @ResultMap("org.spring.springboot.dao.UserDao.sysUserMap")
    @Select("select t.sys_user_id,t.login_no,t.login_pw,r.role_name from "
            + "TS_SYS_USER t left join ts_role r on t.role_id = r.role_id where t.login_no = #{username}")
    @ResultType(SysUser.class)
    SysUser findByUsername(@Param("username") String username);
}

entity

package org.spring.springboot.domain;

public class SysRole
{
    private Long id;

    private String name;

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

}
package org.spring.springboot.domain;


import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;


public class SysUser implements UserDetails
{
    private static final long serialVersionUID = 1L;

    private Long id;

    private String username;

    private String password;

    private List<SysRole> roles;

    /**
     * 用户角色
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities()
    {

        List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
        List<SysRole> roles = this.getRoles();
        if(CollectionUtils.isEmpty(roles)){
            return auths;
        }
        for (SysRole role : roles)
        {
            auths.add(new SimpleGrantedAuthority(role.getName()));
        }
        return auths;
    }

    @Override
    public boolean isAccountNonExpired()
    {
        return true;
    }

    @Override
    public boolean isAccountNonLocked()
    {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired()
    {
        return true;
    }

    @Override
    public boolean isEnabled()
    {
        return true;
    }

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public List<SysRole> getRoles()
    {
        return roles;
    }

    public void setRoles(List<SysRole> roles)
    {
        this.roles = roles;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    public String getUsername()
    {
        return username;
    }

    public String getPassword()
    {
        return password;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值