- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
1
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Resource(name = "userService")
private UserDetailsService userDetailsService;
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth, DataSource dataSource) throws Exception {
/*auth.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("select login as principal, mot_de_passe as credentials, flag_compte_actif as enabled from utilisateur where login = ?")
.authoritiesByUsernameQuery("SELECT utilisateur.login as principal, profil.designation as role FROM utilisateur INNER JOIN user_profil ON utilisateur.id_user = user_profil.iduserpk INNER JOIN profil ON user_profil.idprofilpk = profil.id_profil WHERE utilisateur.login = ? ")
.rolePrefix("ROLE_");
auth.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());*/
auth.inMemoryAuthentication()
.withUser("admin")
.password("password")
.roles("Administrateur");
}
@Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception {
return new JwtAuthenticationFilter();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("Akal configure method begin");
//http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class);
http.cors().and()
.csrf().disable().
authorizeRequests()
.antMatchers("/token/generate").permitAll()
.anyRequest().authenticated()
.and().formLogin().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
System.out.println("Akal configure method");
http
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
// @Bean
// public BCryptPasswordEncoder passwordEncoder(){
// return new BCryptPasswordEncoder();
// }
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
}
@RestController
@CrossOrigin("*")
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private UtilisateurRepository userRepo;
@PostMapping(value = "/token/generate")
public ResponseEntity<?> register(@RequestBody LoginUser loginUser) throws AuthenticationException {
System.out.println("We're in man!");
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginUser.getUsername(),
loginUser.getPassword()
)
);
System.out.println("(Username, Password): (" + loginUser.getUsername() + ", " + loginUser.getPassword() + ")");
SecurityContextHolder.getContext().setAuthentication(authentication);
final Utilisateur user = userRepo.findByLogin(loginUser.getUsername());
final String token = jwtTokenUtil.generateToken(user);
System.out.println("Token Controller Access=> Token Generated: " + token);
return ResponseEntity.ok(new AuthToken(token));
}
}
public class AuthToken {
private String token;
public AuthToken(){
}
public AuthToken(String token){
this.token = token;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
public class CorsFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
System.out.println("Filtering on...........................................................");
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
//response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
String header = req.getHeader("Authorization");
String username = null;
String authToken = null;
if (header != null && header.startsWith("Bearer ")) {
authToken = header.replace("Bearer ","");
try {
username = jwtTokenUtil.getUsernameFromToken(authToken);
} catch (IllegalArgumentException e) {
logger.error("an error occured during getting username from token", e);
} catch (ExpiredJwtException e) {
logger.warn("the token is expired and not valid anymore", e);
} catch(SignatureException e){
logger.error("Authentication Failed. Username or Password not valid.");
}
} else {
logger.warn("couldn't find bearer string, will ignore the header");
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (jwtTokenUtil.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN")));
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(req));
logger.info("authenticated user " + username + ", setting security context");
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
chain.doFilter(req, res);
}
}
@Component
public class JwtTokenUtil implements Serializable {
static final long EXPIRATIONTIME = 864_000_000; // 10 days
static final String SECRET = "secret";
static final String TOKEN_PREFIX = "Bearer";
static final String HEADER_STRING = "Authorization";
public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token)
.getBody();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
public String generateToken(Utilisateur user) {
return doGenerateToken(user.getLogin());
}
private String doGenerateToken(String subject) {
Claims claims = Jwts.claims().setSubject(subject);
claims.put("scopes", Arrays.asList(new SimpleGrantedAuthority("ROLE_Administrateur")));
return Jwts.builder()
.setClaims(claims)
.setIssuer("http://devglan.com")
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
.signWith(SignatureAlgorithm.HS256, SECRET)
.compact();
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token);
return (
username.equals(userDetails.getUsername())
&& !isTokenExpired(token));
}
}
public class LoginUser {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
最佳答案
在 Spring Security 5 中,如果您使用的是 auth.inMemoryAuthentication()
,您将无法使用 BCryptPasswordEncoder
或 StandardPasswordEncoder
.您必须使用自己的 UserDetailsService
以获取用户和密码。或者,如果您需要测试您的代码,只需返回 NoOpPasswordEncoder.getInstance()
在您的 passwordEncoder()
方法
SecurityConfig.class
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AccountService accountService; //your own implementation of UserDetailsService
....
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.eraseCredentials(true)
.userDetailsService(accountService)
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
....
}
@Service
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public class AccountService implements UserDetailsService {
@Autowired
private AccountRepository accountRepository; //Your database repository
@Autowired
private PasswordEncoder passwordEncoder;
@PostConstruct
protected void initialize() {
save(new Account("user", "demo", "ROLE_USER"));
save(new Account("admin", "admin", "ROLE_ADMIN"));
}
@Transactional
public Account save(Account account) {
account.setPassword(passwordEncoder.encode(account.getPassword()));
accountRepository.save(account);
return account;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Account account = accountRepository.findOneByEmail(username);
if(account == null) {
throw new UsernameNotFoundException("user not found");
}
return createUser(account);
}
public void signin(Account account) {
SecurityContextHolder.getContext().setAuthentication(authenticate(account));
}
private Authentication authenticate(Account account) {
return new UsernamePasswordAuthenticationToken(createUser(account), null, Collections.singleton(createAuthority(account)));
}
private User createUser(Account account) {
return new User(account.getEmail(), account.getPassword(), Collections.singleton(createAuthority(account)));
}
private GrantedAuthority createAuthority(Account account) {
return new SimpleGrantedAuthority(account.getRole());
}
}
@SuppressWarnings("serial")
@Entity
@Table(name = "account")
public class Account implements java.io.Serializable {
@Id
@GeneratedValue
private Long id;
@Column(unique = true)
private String email;
@JsonIgnore
private String password;
private String role = "ROLE_USER";
private Instant created;
protected Account() {
}
public Account(String email, String password, String role) {
this.email = email;
this.password = password;
this.role = role;
this.created = Instant.now();
}
public Long getId() {
return id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Instant getCreated() {
return created;
}
}
关于使用 JWT 的 Spring Security 总是返回 401 未经授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52028457/
我们需要实现如下授权规则。 如果用户是 super 管理员,则向他提供所有客户信息。比如订单信息。如果用户是客户管理员,只提供他自己的客户信息。等等 我们计划在 DAO 层实现过滤。 创建通用设计来处
我有 https 设置的 Spring Security。 尝试以安全方式在 URL 上运行 curl GET 时,我看到了意外行为。 当 curl 第一次向服务器发送请求时,它没有授权数据(为什么?
关闭。这个问题是 opinion-based 。它目前不接受答案。 想改进这个问题?更新问题,以便 editing this post 可以用事实和引用来回答它。 1年前关闭。 Improve thi
我正在构建以下内容: 一个 JavaScript 单页应用程序; 一个暴露 RESTful API 的 Node.js 后端,它将存储用户数据; 用户凭据(电子邮件/密码)可以通过单页应用程序创建并存
在带有RESTful Web服务的Spring Boot应用程序中,我已将Spring Security与Spring Social和SpringSocialConfigurer一起配置。 现在,我有
我正在为真实世界组织的成员在 Rails 中构建一个基于社区的站点。我正在努力遵循 RESTful 设计的最佳实践,其中大部分或多或少是书本上的。使我的大脑在整洁的 RESTful 圈子中运转的问题是
我想启用 ABAC mode对于我在 Google 容器引擎中使用的 Kubernetes 集群。 (更具体地说,我想限制自动分配给所有 Pod 的默认服务帐户对 API 服务的访问)。但是,由于 -
奇怪的事情 - 在 git push gitosis 上不会将新用户的 key 添加到/home/git/.ssh/authorized_keys。当然-我可以手动添加 key ,但这不好:( 我能做
我很好奇您提供 的顺序是否正确和元素中的元素重要吗? 最佳答案 是的,顺序很重要。本页介绍了基本原理:http://msdn.microsoft.com/en-us/library/wce3kxhd
我阅读了如何使用 @login_required 的说明以及其他带有解析器的装饰器。但是,如果不使用显式解析器(而是使用默认解析器),如何实现类似的访问控制? 就我而言,我将 Graphite 烯与
我用 php 开发了一个审核应用程序,通过它我可以审核所有帖子和评论。我还可以选择在 Facebook 粉丝页面墙上发布帖子。但是,当我尝试这样做时,会引发异常,显示“用户尚未授权应用程序执行此操作”
我使用 jquery-ajax 方法 POST 来发布授权 header ,但 Firebug 显示错误“401 Unauthorized” header 作为该方法的参数。 我做错了什么?我该怎么办
我有两组用户,一组正在招聘,一组正在招聘。 我想限制每个用户组对某些页面的访问,但是当我在 Controller 中使用 [Authorize] 时,它允许访问任何已登录的用户而不区分他们来自哪个组?
我有一个简单直接的授权实现。好吧,我只是认为我这样做,并且我想确保这是正确的方法。 在我的数据库中,我有如下表:users、roles、user_role、permissions、 role_perm
我的 soap 连接代码: MessageFactory msgFactory = MessageFactory.newInstance(); SOAPMessage message
我想知道是否可以将 mysql 用户设置为只对数据库中的特定表或列具有读取权限? 最佳答案 是的,您可以使用 GRANT 为数据库在细粒度级别执行此操作。见 http://dev.mysql.com/
我试图获得发布流和离线访问的授权,但出现此错误。 而且它没有显示我想要获得的权限。我的代码如下: self.fb = [[Facebook alloc] initWithAppId:@"xxxxxxx
我是 NodeJS 的初学者,我尝试使用 NodeJS + Express 制作身份验证表单。我想对我的密码进行验证(当“confirmpassword”与“password”不同时,它应该不返回任何
我能够为测试 paypal 帐户成功生成访问 token 和 TokenSecret。然而,下一步是为调用创建授权 header 。 在这种情况下,我需要提供我不确定的 Oauth 签名或 API 签
我正在尝试获取授权 steam 页面的 html 代码,但我无法登录。我的代码是 public string tryLogin(string EXP, string MOD, string TIME)
我是一名优秀的程序员,十分优秀!