Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我正在尝试实现spring安全,我配置了所有的东西,但仍然不起作用。

我正在尝试实现spring安全,我配置了所有的东西,但仍然不起作用。
EN

Stack Overflow用户
提问于 2021-11-15 22:59:14
回答 1查看 114关注 0票数 0

spring安全性不使用来自数据库的详细信息进行身份验证和在控制台中生成密码,也不使用我的自定义登录表单。

主类--

代码语言:javascript
运行
AI代码解释
复制
package mis.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@ComponentScan({"mis.controller", "mis.services"})
@EntityScan("mis.entity")
@EnableJpaRepositories("mis.dao")
public class BitmisApplication {

    public static void main(String[] args) {
        SpringApplication.run(BitmisApplication.class, args);
    }

}

CustomUserDetails--

代码语言:javascript
运行
AI代码解释
复制
package mis.config;

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

import mis.entity.Roles;
import mis.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;


public class CustomUserDetails implements UserDetails {
    
    private User user;
    
    public CustomUserDetails(User user) {
        this.user = user;
    }
 
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<Roles> roles = user.getRoles();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
         
        for (Roles role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
         
        return authorities;
    }
 
    @Override
    public String getPassword() {
        return user.getPassword();
    }
 
    @Override
    public String getUsername() {
        return user.getUsername();
    }
 
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
 
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
 
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
 
    @Override
    public boolean isEnabled() {
        return user.isEnabled();
    }
    
}

MyConfig类--

代码语言:javascript
运行
AI代码解释
复制
package mis.config;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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 org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;



@Configuration
@EnableAutoConfiguration
@EnableWebSecurity
public class MyConfig extends WebSecurityConfigurerAdapter {
    
    
    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsServiceImpl();
    }
     
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
     
    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService());
        authProvider.setPasswordEncoder(passwordEncoder());
         
        return authProvider;
    }
 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/").hasAnyAuthority("USER", "CREATOR", "EDITOR", "ADMIN")
            .antMatchers("/new").hasAnyAuthority("ADMIN", "CREATOR")
            .antMatchers("/admin/**").hasAnyAuthority("ADMIN", "EDITOR")
            .antMatchers("/delete/**").hasAuthority("ADMIN")
            .anyRequest().authenticated()
            .and()
            .formLogin().permitAll()
            .and()
            .logout().permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/403")
            ;
    }
}

UserDetailsServiceImpl--

代码语言:javascript
运行
AI代码解释
复制
package mis.config;

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;
import mis.entity.User;
import mis.dao.UserRepository;

public class UserDetailsServiceImpl implements UserDetailsService {
    
        @Autowired
        private UserRepository userRepository;
         
        @Override
        public UserDetails loadUserByUsername(String username)
                throws UsernameNotFoundException {
            User user = userRepository.getUserByUsername(username);
          
            if (user == null) {
                throw new UsernameNotFoundException("Could not find user");
            }
             
            return new CustomUserDetails(user);
        }

}

UserRepository--

“包装mis.dao;

代码语言:javascript
运行
AI代码解释
复制
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import mis.entity.User;

public interface UserRepository extends JpaRepository<User, Long> {
    @Query("SELECT u FROM User u WHERE u.username = :username")
    public User getUserByUsername(@Param("username") String username);
}"

我认为springboot无法读取这个身份验证文件。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-16 09:49:23

spring应用程序找不到您的信任,因为您的项目结构是错误的,并且您已经添加了错误的自定义配置。

默认情况下,@SpringBootApplication类将扫描它在mis.main中的包以及这个包下面的所有包(mis.main.*等),以便找到所有春季注释类并加载它们。

您已经将您的配置文件放置在mis.config中,该文件不位于mis.main的直接下面,而mis.entity中的文件也不在mis.main下面。

你还增加了

代码语言:javascript
运行
AI代码解释
复制
@ComponentScan({"mis.controller", "mis.services"})
@EntityScan("mis.entity")

为了尝试查找配置文件,但未能将mis.config指定为要扫描的文件夹。

最简单的解决办法是

  • 移除上面提到的两个注释。
  • 将主类移动到包mis中,然后删除包mis.main,以便主类位于项目根。

其他一些事情:

代码语言:javascript
运行
AI代码解释
复制
@Bean
public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService());
    authProvider.setPasswordEncoder(passwordEncoder());
         
    return authProvider;
}
 
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider());
}

不需要,并且可以删除,因为您已经将自定义UserDetailsServicePasswordEncoder声明为bean,它们将由系统自动提取并包含到spring中,并且它将自动为您设置DaoAuthentication。

如果您正在学习,您应该阅读spring安全参考文档--这里提到了所有这些。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69984937

复制
相关文章
20.4 shell脚本中的变量
shell脚本中的变量 当脚本中使用某个字符串较频繁并且字符串长度很长时就应该使用变量代替 使用条件语句时,常使用变量 if [ $a -gt 1 ]; then ... ; fi 引用某个命令的结果时,用变量替代 n=wc -l 1.txt 写和用户交互的脚本时,变量也是必不可少的 read -p "Input a number: " n; echo 内置变量 0, 1, 2… 0表示脚本本身,1 第一个参数,2 第二个 .... 数学运算a=1;b=2; c=((a+b))或者[a+b]
运维小白
2022/01/06
3.2K0
Shell脚本——变量
variable 是变量名,value 是赋给变量的值。如果 value 不包含任何空白符(例如空格、Tab 缩进等),那么可以不使用引号;如果 value 包含了空白符,那么就必须使用引号包围起来。使用单引号和使用双引号也是有区别的,稍后我们会详细说明。
栗筝i
2022/12/01
1.6K0
C代码中如何使用链接脚本中定义的变量?
https://sourceware.org/ml/binutils/2007-07/msg00154.html
韦东山
2020/09/30
4.3K0
shell脚本介绍、shell脚本结构和执行、date命令用法、shell脚本中的变量
转载于:https://blog.51cto.com/8043410/2175024
全栈程序员站长
2021/06/17
1.8K0
shell脚本介绍、shell脚本结构和执行、date命令用法、shell脚本中的变量
Bash 脚本中,特殊变量$0到底是什么?
在 Bash 脚本中,$0 是一个特殊变量,它代表当前脚本的路径和名称。这个变量用于表示脚本自身,它是 Bash 环境中的一个重要组成部分。$0 变量是一个只读变量,无法更改。
网络技术联盟站
2023/05/03
2.7K0
Bash 脚本中,特殊变量$0到底是什么?
Shell脚本之特殊变量
Linux系统Shell脚本特殊变量 $0, $$, $?, $#, $*, $@ 1 Shell脚本特殊变量 当前脚本的名字 2 $*和$@的区别 当脚本传递的参数都不被双引号""包含时, $*和
Qt君
2019/07/15
6600
shell脚本介绍,shell脚本结构和执行方式,date命令的用法,shell脚本中的变量简介
  Shell Script,Shell脚本与Windows/Dos下的批处理相似,也就是用各类命令预先放入到一个文件中,方便一次性执行的一个程序文件,主要是方便管理员进行设置或者管理用的。但是它比Windows下的批处理更强大,比用其他编程程序编辑的程序效率更高,它使用了Linux/Unix下的命令。
端碗吹水
2020/09/23
2.7K0
shell脚本介绍,shell脚本结构和执行方式,date命令的用法,shell脚本中的变量简介
python调用bat脚本并向bat脚本传递list变量
我用的是subprocess.call的方法,但是无法传递变量,求大神指点,希望可以实现python调用bat脚本并向bat脚本传递list变量
用户7542547
2020/07/09
3.1K0
Asp.net Ajax Accordion控件的用法
Accordion,翻译过来是“手风琴、可折叠”的意思,微软Asp.net ajax提供了Accordion可折叠面板控件,方便用户在系统菜单、信息展示中使用,用户体验是相当的好啊。
拓荒者IT
2019/09/26
1.7K0
SHELL(bash)脚本编程一:变量
本篇开始,介绍shell脚本编程,更确切的说是bash脚本编程(版本:4.2.46(1)-release)。我们从变量开始。
用户5030870
2019/04/11
2.8K0
shel脚本基础系列(一)变量
虽然自己是一名java程序员,做后端的,但是最近工作中经常需要看别人写的脚本去运行项目,所以作为后端程序员,我们也需要了解一下shell语法,会读懂一些基本的shell脚本。
jiankang666
2022/05/12
2920
Linux系统 awk sed R脚本 python脚本传入变量
sed 传入变量: 1 chrI="chr2";sed -n "/$chrI/p" clippointpos.csv #变量用$var表示,把sed的单引号变为双引号即可 awk 传入变量: 1 chrI="chr2";awk '/"'$chrI'"/{print $0}' clippointpos.csv #变量用$var表示,变量两边再加上"' R脚本传入变量: 1 arg <- commandArgs(T) 2 filename=arg[1] 3 outputfile=arg[2] python
用户1680321
2022/03/10
1.5K0
Shell脚本应用(shell脚本基础与shell变量)
1、shell:命令解释器 1)可支持的shell保存在/etc/shells中 2)默认shell为/bin/bash 2、shell脚本编写: 1)使用vi编辑器 2)每行一条命令,依次执行 3)赋予可执行权限(x) 3、执行方式: 1)脚本文件路径:有两种,相对和绝对路径,必须有x权限 2)Sh脚本文件路径:无须x权限,相对和绝对路径都可以,在子shell上 3)Source(或 .)脚本文件路径:无须x权限,在当前sell执行 4、脚本组成: 1)脚本声明:指定脚本执行的shell,以#!开头
L宝宝聊IT
2018/06/20
1.7K0
beanshell入门:脚本中引用自定义的变量和方法和定义运行时变量
Beanshell (bsh) 是用Java写成的,一个小型的、免费的、可以下载的、嵌入式的Java源代码解释器,具有对象脚本语言特性。
10km
2022/09/26
2K0
JSP定义_JSP声明变量与普通脚本变量的区别
在JSP中用两种声明变量的方法,一种是在<%! %>内,一种是在<% %>内。他们之间有什么区别呢?我们直接看一个JSP文件来理解。
全栈程序员站长
2022/11/03
2.3K0
shell脚本快速入门系列之------变量
为灵活管理Linux系统提供特定参数,有两层意思 变量名:使用固定的名称,由系统预设或用户定义 变量值:能够根据用户设置,系统环境的变化而变化
不吃小白菜
2020/09/03
6190
shell脚本export变量只限脚本内么_shell脚本调用oracle存储过程
用sh运行脚本后,在当前shell利用命令env查看环境变量,但是却没有fdu变量,难道是因为我的export语句没有生效?
全栈程序员站长
2022/10/04
1.5K0
linux 环境变量&脚本编程之系统环境与变量
https://wizardforcel.gitbooks.io/vbird-linux-basic-4e/content/104.html
yurric
2023/10/18
1630
Linux教程 - 在Shell脚本中声明和使用布尔变量示例
作者:Linux迷链接:https://www.linuxmi.com/shell-boolean-variables.html
用户6543014
2021/01/07
18.3K0
使用javax.script包实现Java设置JS脚本中的变量
下面例子中,我们通过javax.script包ScriptEngine.put()方法设置JS脚本中的变量,JS把所有在线用户输出。
I Teach You 我教你
2023/07/18
3110

相似问题

在鼠标悬停时显示DIV

20

在鼠标悬停时显示div

41

在鼠标悬停时使用fadeInUp显示div,鼠标悬停时显示fadeOutDown

32

Bootstrap在鼠标悬停时显示div

20

在鼠标悬停时显示div对象?

21
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档