"org.springframework.security:spring-security-web:4.1.0.RELEASE","org.springframework.security:spring-security-taglibs:4.1.0.RELEASE","org.springframework.security:spring-security-config:4.1.0.RELEASE"
configure(WebSecurity web)
@Override
public void configure(WebSecurity web) throws Exception {
// 设置不拦截规则
web.ignoring().antMatchers("/pm/**","/common/**","/*.ico");
}
configure(HttpSecurity http)
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").anonymous();//指定登录界面容许匿名登录
http.authorizeRequests() .anyRequest().authenticated()
//容许嵌入框架iframe
.and().headers().frameOptions().disable() .and() .httpBasic()
//defaultSuccessUrl:指定登录成功后界面, loginPage:指定登录界面
.and().formLogin().defaultSuccessUrl("/main.to").loginPage("/login") .permitAll();
}
1.容许嵌入框架iframe跳转
.and().headers().frameOptions().disable()
2.指定登录界面
.and().formLogin().loginPage("/login")
3.指定登录成功后返回界面
.and().formLogin().defaultSuccessUrl("/main.to")
进入后台时进行权限验证
package com.framework.security;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
/****
* @author tzz
* @功能描述
* @date 2016/5/5
* 修改人 修改时间 修改说明
****/
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig{
}
后台函数权限验证(范例)
@PreAuthorize("hasRole('002_02_202')")
@ResponseBody
@RequestMapping(value="/company.add", method = RequestMethod.POST,params={"nameShort","name","remark"})
public Map add(String name,String nameShort, String remark) {
....
}
1.自定义盐值加密配置
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
ReflectionSaltSource saltSource = new ReflectionSaltSource();
//UserInfo.salt 盐值数据字段
saltSource.setUserPropertyToUse("salt");
authProvider.setPasswordEncoder(new Md5PasswordEncoder());
auth.authenticationProvider(authProvider);
自定义用户信息SQL
private String usersByUsernameQuery = "SELECT account,pwd,stat,salt,id,company_id,name,login_stat,login_date ,login_ip FROM USER_ACCOUNT WHERE ACCOUNT = ?"
自定义权限信息SQL
private String authoritiesByUsernameQuery = "SELECT NAME,POWER_CODE FROM VW_USER_POWER WHERE ACCOUNT_ID = ?"
自定义用户权限信息对 configure(AuthenticationManagerBuilder auth)进行修改
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
ReflectionSaltSource saltSource = new ReflectionSaltSource();
saltSource.setUserPropertyToUse("salt");
authProvider.setSaltSource(saltSource);
authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(new Md5PasswordEncoder());
auth.authenticationProvider(authProvider);
}
protected UserInfoService userDetailsService() {
return new UserInfoService().setAuthoritiesUsernameQuery(this.authoritiesByUsernameQuery)
.setUsersUsernameQuery(this.usersByUsernameQuery).dataSource(dataSource);
}
package com.framework.security;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import javax.sql.DataSource;
import java.util.*;
/****
* @author tzz
* @功能描述
* @date 2016/5/3
* 修改人 修改时间 修改说明
****/
public class UserInfoService extends JdbcUserDetailsManager implements UserDetailsService {
private Map userMap = null;
protected final Log logger = LogFactory.getLog(getClass());
protected final MessageSourceAccessor messages = SpringSecurityMessageSource
.getAccessor();
private String usersByUsernameQuery;
private String authoritiesByUsernameQuery;
public UserInfoService() {
userMap = new HashMap<>();
}
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
List users = loadUsersByUsername(username);
if (users.size() == 0) {
logger.debug("Query returned no results for user '" + username + "'");
throw new UsernameNotFoundException(messages.getMessage(
"JdbcDaoImpl.notFound", new Object[] { username },
"Username {0} not found"));
}
UserInfo user = (UserInfo)users.get(0);
Set dbAuthsSet = new HashSet();
if (getEnableAuthorities()) {
dbAuthsSet.addAll(loadUserAuthorities(user.getId()));
}
if (getEnableGroups()) {
dbAuthsSet.addAll(loadGroupAuthorities(user.getUsername()));
}
List dbAuths = new ArrayList(dbAuthsSet);
addCustomAuthorities(user.getUsername(), dbAuths);
if (dbAuths.size() == 0) {
logger.debug("User '" + username
+ "' has no authorities and will be treated as 'not found'");
throw new UsernameNotFoundException(messages.getMessage(
"JdbcDaoImpl.noAuthority", new Object[] { username },
"User {0} has no GrantedAuthority"));
}
return createUserDetails(username,user,dbAuths);
}
protected UserDetails createUserDetails(String username,
UserInfo userFromUserQuery, List combinedAuthorities) {
String returnUsername = userFromUserQuery.getUsername();
if (!isUsernameBasedPrimaryKey()) {
returnUsername = username;
}
UserInfo user = new UserInfo(returnUsername,userFromUserQuery.getPassword(), userFromUserQuery.isEnabled(), true, true, true,
combinedAuthorities);
user.setId(userFromUserQuery.getId());
user.setCompanyId(userFromUserQuery.getCompanyId());
user.setName(userFromUserQuery.getName());
user.setLoginStat(userFromUserQuery.getLoginStat());
user.setLoginDate(userFromUserQuery.getLoginDate());
user.setLoginIP(userFromUserQuery.getLoginIP());
user.setSalt(userFromUserQuery.getSalt());
return user;
}
/**
* Loads authorities by executing the SQL from
* groupAuthoritiesByUsernameQuery.
*
* @return a list of GrantedAuthority objects for the user
*/
protected List loadUserAuthorities(int userId) {
try {
return getJdbcTemplate().query(this.authoritiesByUsernameQuery,
new Object[] { userId },(RowMapper) (rs,rowNum)-> {
String roleName = getRolePrefix() + rs.getString(2);
return new SimpleGrantedAuthority(roleName);
});
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Loads authorities by executing the SQL from authoritiesByUsernameQuery.
*
* @return a list of GrantedAuthority objects for the user
*/
protected List loadUsersByUsername(String username) {
try {
return getJdbcTemplate().query(this.usersByUsernameQuery, new Object[] { username},
(RowMapper) (rs, rowNum) -> {
String username1 = rs.getString(1);
String password = rs.getString(2);
boolean enabled = rs.getBoolean(3);
UserInfo user = new UserInfo(username1, password, enabled, true, true, true,
AuthorityUtils.NO_AUTHORITIES);
user.setSalt(rs.getString(4));
user.setId(rs.getInt(5));
user.setCompanyId(rs.getInt(6));
user.setName(rs.getString(7));
user.setLoginStat(rs.getInt(8));
user.setLoginDate(rs.getLong(9));
user.setLoginIP(rs.getString(10));
return user;
}
);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public UserInfoService setAuthoritiesUsernameQuery(String authoritiesByUsernameQuery) {
this.authoritiesByUsernameQuery = authoritiesByUsernameQuery;
return this;
}
public UserInfoService setUsersUsernameQuery(String usersByUsernameQuery) {
this.usersByUsernameQuery = usersByUsernameQuery;
return this;
}
public UserInfoService dataSource(DataSource dataSource) {
super.setDataSource(dataSource);
return this;
}
}
package com.framework.security;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
/****
* @author tzz
* @功能描述
* @date 2016/5/3
* 修改人 修改时间 修改说明
****/
public class UserInfo extends User {
private int id;
private int companyId;//所属公司
private int loginSystemId = 0;//当前登录系统ID
private String name;//用户名称
private int loginStat;//登录状态 1:登录 2:未登陆
private String loginIP;//登录IP
private long loginDate;//登录时间
private String salt;
public UserInfo(String username, String password, Collection extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
public UserInfo(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCompanyId() {
return companyId;
}
public void setCompanyId(int companyId) {
this.companyId = companyId;
}
public int getLoginSystemId() {
return loginSystemId;
}
public void setLoginSystemId(int loginSystemId) {
this.loginSystemId = loginSystemId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLoginStat() {
return loginStat;
}
public void setLoginStat(int loginStat) {
this.loginStat = loginStat;
}
public String getLoginIP() {
return loginIP;
}
public void setLoginIP(String loginIP) {
this.loginIP = loginIP;
}
public long getLoginDate() {
return loginDate;
}
public void setLoginDate(long loginDate) {
this.loginDate = loginDate;
}
}