@Component 和 @PreAuthorize 问题

今天尝试用 spring security 来保护 业务层 的方法。使用了@PreAuthorize
定义一个 接口 IUser

public interface IUser {
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public void say();

}



@PreAuthorize注解定义了当 拥有 ROLE_ADMIN 权限的时候才能够正确的使用这个方法. hasRole("XX")是 spEL的语法.
这就是保证合法、已认证的用户才能访问修改密码功能所要做的所有事情。Spring Security将会使用运行时的面向方面编程的切点(aspect oriented programming (AOP) pointcut)来对方法执行before advice,并在安全要求未满足的情况下抛出AccessDeniedException异常。


定义一个实现类:UserSerivece
@Component("userService")
public class UserSerivece implements IUser {
public class UserSerivece implements IUser {
@Overridepublic void say() {System.out.println("我访问了say方法");}}


spring-security 中加入:
只需要在 <http> 声明之前,添加下面的元素即可: 
<global-method-security pre-post-annotations="enabled"/>



为了方便,直接在 。xml定义如下两个用户:

<user-service>
			<user name="admin" authorities="ROLE_USER,ROLE_ADMIN" password="admin"/>
			<user name="user" authorities="ROLE_USER" password="user"/>
			
		</user-service>




因为我使用spring mvc 定义个如下Controller:
@Controller
public class BaseControle {
	private IUser userService;
   @RequestMapping(value="/lookup")
	public String testIn(){
		for(GrantedAuthority authority:SecurityContextHolder.getContext().getAuthentication().getAuthorities())
		{
			System.out.println(authority.getAuthority());
			
		}
		userService.say();
		
		
		return "content";
	}
	public IUser getUserService() {
		return userService;
	}


	@Resource(name="userService")
	public void setUserService(IUser userService) {
		this.userService = userService;
	}
}





我用 user 登入,结果发现我竟然可以访问这个方法。。当时那个郁闷啊。。。
后来再网上查资料
发现service层Spring没有使用注解,而是在配置文件中配置bean元素,于是把@Component去掉,添加一个bean

<bean id="userService" class="com.security.service.UserSerivece"/>




就可以了。 越权访问,就会出现如下界面.




 呵呵。没碰到这个问题还真不知道还spring没有个service定义注解。。




Spring Security可以使用JWT(JSON Web Token)来验证用户的身份和权限。 1.添加JWT依赖项:在pom.xml文件中添加以下依赖项: ``` <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> ``` 2.创建JWT工具类:创建一个JWT工具类来生成和验证JWT。 ``` import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Component; import java.util.Date; @Component public class JwtUtils { private final String JWT_SECRET = "mysecretkey"; private final int JWT_EXPIRATION_MS = 86400000; public String generateJwtToken(Authentication authentication) { User user = (User) authentication.getPrincipal(); return Jwts.builder() .setSubject((user.getUsername())) .setIssuedAt(new Date()) .setExpiration(new Date((new Date()).getTime() + JWT_EXPIRATION_MS)) .signWith(SignatureAlgorithm.HS512, JWT_SECRET) .compact(); } public boolean validateJwtToken(String authToken) { try { Jwts.parser().setSigningKey(JWT_SECRET).parseClaimsJws(authToken); return true; } catch (Exception e) { e.printStackTrace(); } return false; } public String getUsernameFromJwtToken(String token) { return Jwts.parser() .setSigningKey(JWT_SECRET) .parseClaimsJws(token) .getBody().getSubject(); } } ``` 3.创建JWT过滤器:创建一个JWT过滤器来验证JWT并设置用户的身份和权限。 ``` import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import com.example.demo.security.services.UserDetailsServiceImpl; import io.jsonwebtoken.ExpiredJwtException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class JwtAuthTokenFilter extends OncePerRequestFilter { @Autowired private JwtUtils jwtUtils; @Autowired private UserDetailsServiceImpl userDetailsService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { try { String jwt = parseJwt(request); if (jwt != null && jwtUtils.validateJwtToken(jwt)) { String username = jwtUtils.getUsernameFromJwtToken(jwt); UserDetails userDetails = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (ExpiredJwtException e) { logger.error("JWT token is expired: {}", e.getMessage()); } catch (Exception e) { logger.error("Cannot set user authentication: {}", e.getMessage()); } chain.doFilter(request, response); } private String parseJwt(HttpServletRequest request) { String headerAuth = request.getHeader("Authorization"); if (headerAuth != null && headerAuth.startsWith("Bearer ")) { return headerAuth.substring(7, headerAuth.length()); } return null; } } ``` 4.配置Spring Security:在Spring Security配置中添加JWT过滤器。 ``` import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; 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; import com.example.demo.security.jwt.JwtAuthTokenFilter; import com.example.demo.security.services.UserDetailsServiceImpl; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity( // securedEnabled = true, // jsr250Enabled = true, prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtAuthTokenFilter jwtAuthTokenFilter; @Autowired private UserDetailsServiceImpl userDetailsService; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService); authProvider.setPasswordEncoder(bCryptPasswordEncoder); return authProvider; } @Override public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/api/auth/**").permitAll() .anyRequest().authenticated(); http.addFilterBefore(jwtAuthTokenFilter, UsernamePasswordAuthenticationFilter.class); } } ``` 现在,Spring Security将使用JWT来验证用户的身份和权限。您可以在需要身份验证和授权的端点上使用Spring Security注释,例如@PreAuthorize和@PostAuthorize
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值