springboot+mybatis实现security

来源:互联网 发布:windows网络编程案例 编辑:程序博客网 时间:2024/05/18 11:25

代码如下

package com.yjp;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;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 com.yjp.service.DemoService;import com.yjp.service.UserDetailsServiceImpl;@Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter{@Autowiredprivate UserDetailsServiceImpl uds;protected void configure(HttpSecurity http) throws Exception{http.authorizeRequests().antMatchers("/","/home").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().permitAll();}@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{//auth.inMemoryAuthentication().withUser("wangdan").password("123456").roles("USER");auth.userDetailsService(uds);}}
package com.yjp.service;import java.util.ArrayList;import java.util.Collection;import org.springframework.beans.factory.annotation.Autowired;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.stereotype.Service;import com.yjp.model.Demo;@Servicepublic class UserDetailsServiceImpl implements UserDetailsService{@Autowiredprivate DemoService demoService;public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {Demo demo=demoService.findDemo(username);Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();          authorities.add(new SimpleGrantedAuthority("USER"));        return new org.springframework.security.core.userdetails.User(demo.getName(), demo.getPassword(), authorities);}}



0 0
原创粉丝点击