前端传过来的参数key1:{"username":"username","password":"1234"},value->null;key2:{"token"}value->{"123"},怎么使用josnarray获取password里面的"1234"参数
时间: 2023-10-10 22:09:27 浏览: 63
要使用JSON数组获取"password"参数中的值"1234",你需要先将传过来的参数解析为JSON对象,然后通过对象的属性名获取对应的值。在这种情况下,你可以使用以下代码来实现:
```javascript
// 假设前端传来的参数存储在变量data中
const data = {
key1: {
"username": "username",
"password": "1234"
},
key2: {
"token": "123"
}
};
// 解析key1的值为JSON对象
const key1Obj = JSON.parse(data.key1);
// 获取password参数的值
const passwordValue = key1Obj.password;
console.log(passwordValue); // 输出 "1234"
```
相关问题
帮我写一个简单的demo项目,springboot+shiro+jwt+mybatis,数据库表1:user(id, username, password),表2:role(id, rolename),表3:permissions(id, permissionsname),写出所有代码,不需要数据库代码和pmo.xml代码
好的,下面是一个简单的demo项目,基于Spring Boot集成Shiro和JWT进行权限控制,使用MyBatis操作数据库。
1. 创建一个Spring Boot项目,引入相关依赖:
```
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
```
2. 配置Shiro相关的Bean和JWT相关的Bean,创建一个ShiroConfig类,并添加以下内容:
```
@Configuration
public class ShiroConfig {
@Bean
public Realm realm() {
// 创建自定义的Realm
return new MyRealm();
}
@Bean
public SecurityManager securityManager() {
// 创建SecurityManager,并设置Realm
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm());
return securityManager;
}
@Bean
public ShiroFilterFactoryBean shiroFilter() {
// 创建ShiroFilterFactoryBean,并设置SecurityManager和拦截器
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
shiroFilter.setSecurityManager(securityManager());
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/**", "jwt");
shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilter;
}
@Bean
public JwtRealm jwtRealm() {
// 创建JwtRealm
return new JwtRealm();
}
@Bean
public JwtFilter jwtFilter() {
// 创建JwtFilter
return new JwtFilter();
}
}
```
3. 配置MyBatis相关的Bean,创建一个MyBatisConfig类,并添加以下内容:
```
@Configuration
@MapperScan("com.example.demo.mapper")
public class MyBatisConfig {
@Bean
public DataSource dataSource() {
// 创建H2数据库
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql")
.build();
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
// 创建SqlSessionFactory,并设置DataSource和Mapper
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sessionFactory.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"));
return sessionFactory.getObject();
}
}
```
4. 创建一个User实体类,包含id、username和password字段。
```
public class User {
private Long id;
private String username;
private String password;
// getter和setter方法省略
}
```
5. 创建一个Role实体类,包含id和roleName字段。
```
public class Role {
private Long id;
private String roleName;
// getter和setter方法省略
}
```
6. 创建一个Permission实体类,包含id和permissionName字段。
```
public class Permission {
private Long id;
private String permissionName;
// getter和setter方法省略
}
```
7. 创建一个UserMapper接口,定义对User表的操作。
```
@Mapper
public interface UserMapper {
User findByUsername(String username);
}
```
8. 创建一个RoleMapper接口,定义对Role表的操作。
```
@Mapper
public interface RoleMapper {
List<Role> findByUserId(Long userId);
}
```
9. 创建一个PermissionMapper接口,定义对Permission表的操作。
```
@Mapper
public interface PermissionMapper {
List<Permission> findByRoleId(Long roleId);
}
```
10. 创建一个UserService类,添加以下内容:
```
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Autowired
private PermissionMapper permissionMapper;
public User findByUsername(String username) {
return userMapper.findByUsername(username);
}
public List<Role> findRolesByUserId(Long userId) {
return roleMapper.findByUserId(userId);
}
public List<Permission> findPermissionsByRoleId(Long roleId) {
return permissionMapper.findByRoleId(roleId);
}
}
```
11. 创建一个JwtUtils类,添加以下内容:
```
public class JwtUtils {
private static final String SECRET_KEY = "mysecretkey"; // 密钥
private static final long EXPIRATION_TIME = 60 * 60 * 24 * 7; // 过期时间,单位为秒
// 生成JWT
public static String generateToken(String username) {
Date now = new Date();
Date expirationDate = new Date(now.getTime() + EXPIRATION_TIME * 1000);
return Jwts.builder()
.setSubject(username)
.setIssuedAt(now)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
}
// 解析JWT
public static Claims parseToken(String token) {
return Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody();
}
// 验证JWT
public static boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}
}
```
12. 创建一个JwtRealm类,继承AuthorizingRealm类,添加以下内容:
```
public class JwtRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
// 支持JwtToken
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof JwtToken;
}
// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = (String) principals.getPrimaryPrincipal();
List<Role> roles = userService.findRolesByUserId(1L); // 假设用户ID为1
List<String> roleNames = roles.stream().map(Role::getRoleName).collect(Collectors.toList());
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.addRoles(roleNames);
for (Role role : roles) {
List<Permission> permissions = userService.findPermissionsByRoleId(role.getId());
List<String> permissionNames = permissions.stream().map(Permission::getPermissionName).collect(Collectors.toList());
authorizationInfo.addStringPermissions(permissionNames);
}
return authorizationInfo;
}
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
User user = userService.findByUsername(username);
if (user == null) {
throw new UnknownAccountException();
}
return new SimpleAuthenticationInfo(username, user.getPassword(), getName());
}
}
```
13. 创建一个JwtToken类,实现AuthenticationToken接口,添加以下内容:
```
public class JwtToken implements AuthenticationToken {
private String token;
public JwtToken(String token) {
this.token = token;
}
@Override
public Object getPrincipal() {
return JwtUtils.parseToken(token).getSubject();
}
@Override
public Object getCredentials() {
return token;
}
}
```
14. 创建一个JwtFilter类,继承BasicHttpAuthenticationFilter类,添加以下内容:
```
public class JwtFilter extends BasicHttpAuthenticationFilter {
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
String token = getToken(request);
if (token == null || !JwtUtils.validateToken(token)) {
return false;
}
JwtToken jwtToken = new JwtToken(token);
try {
getSubject(request, response).login(jwtToken);
return true;
} catch (Exception e) {
return false;
}
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
response.setContentType("application/json;charset=UTF-8");
try {
PrintWriter out = response.getWriter();
out.write("{\"code\":401,\"message\":\"未登录\"}");
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private String getToken(ServletRequest request) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String token = httpServletRequest.getHeader("Authorization");
if (StringUtils.isNotEmpty(token) && token.startsWith("Bearer ")) {
return token.substring(7);
}
return null;
}
}
```
15. 创建一个UserController类,添加以下内容:
```
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public String login(String username, String password) {
User user = userService.findByUsername(username);
if (user == null || !user.getPassword().equals(password)) {
return "{\"code\":401,\"message\":\"用户名或密码错误\"}";
}
String token = JwtUtils.generateToken(username);
return "{\"code\":200,\"message\":\"登录成功\",\"token\":\"" + token + "\"}";
}
@GetMapping("/user")
@RequiresPermissions("user:view")
public String viewUser() {
return "View User";
}
}
```
以上是一个简单的demo项目,实现了基于Spring Boot集成Shiro和JWT进行权限控制,使用MyBatis操作数据库。需要注意的是,这里的代码仅供参考,具体实现还需要根据实际情况进行调整。
springboot security项目 如何封装jwt 及token 其中数据表为package com.aokace.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; /** * <p> * * </p> * * @author aokace * @since 2023-05-23 */ @Getter @Setter @TableName("user") @ApiModel(value = "User对象", description = "") public class User implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "userid", type = IdType.AUTO) private Integer userid; @TableField("authority") private String authority; @TableField("role") private String role; @TableField("username") private String username; @TableField("password") private String password; }
首先需要引入相关的依赖,包括JWT和Spring Security的依赖:
```
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
然后创建一个JwtTokenUtil类来实现JWT的签发和验证功能:
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtTokenUtil {
private static final String CLAIM_KEY_USERNAME = "sub";
private static final String CLAIM_KEY_CREATED = "created";
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
claims.put(CLAIM_KEY_CREATED, new Date());
return generateToken(claims);
}
public String getUsernameFromToken(String token) {
String username;
try {
Claims claims = getClaimsFromToken(token);
username = claims.getSubject();
} catch (Exception e) {
username = null;
}
return username;
}
public Date getCreatedDateFromToken(String token) {
Date created;
try {
Claims claims = getClaimsFromToken(token);
created = new Date((Long) claims.get(CLAIM_KEY_CREATED));
} catch (Exception e) {
created = null;
}
return created;
}
public Date getExpirationDateFromToken(String token) {
Date expiration;
try {
Claims claims = getClaimsFromToken(token);
expiration = claims.getExpiration();
} catch (Exception e) {
expiration = null;
}
return expiration;
}
public boolean isTokenExpired(String token) {
Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
public String refreshToken(String token) {
String refreshedToken;
try {
Claims claims = getClaimsFromToken(token);
claims.put(CLAIM_KEY_CREATED, new Date());
refreshedToken = generateToken(claims);
} catch (Exception e) {
refreshedToken = null;
}
return refreshedToken;
}
public boolean validateToken(String token, UserDetails userDetails) {
String username = getUsernameFromToken(token);
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
}
private Claims getClaimsFromToken(String token) {
Claims claims;
try {
claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
claims = null;
}
return claims;
}
private String generateToken(Map<String, Object> claims) {
Date expirationDate = new Date(System.currentTimeMillis() + expiration * 1000);
JwtBuilder builder = Jwts.builder()
.setClaims(claims)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, secret);
return builder.compact();
}
}
```
其中,JwtTokenUtil类中的generateToken方法用于生成JWT Token,getUsernameFromToken和getExpirationDateFromToken方法用于解析JWT Token中的用户名和过期时间,isTokenExpired方法用于判断JWT Token是否已经过期,refreshToken方法用于刷新JWT Token,validateToken方法用于验证JWT Token是否有效,getClaimsFromToken方法用于从JWT Token中获取Claims。
然后在Spring Security的配置类中添加JwtTokenFilter来实现JWT的过滤和验证:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
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.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtTokenFilter jwtTokenFilter;
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
```
其中,SecurityConfig类中的configure方法用于配置Spring Security的策略,addFilterBefore方法用于添加JwtTokenFilter,authenticationManagerBean方法用于获取AuthenticationManager。
最后,在登录接口中,使用JwtTokenUtil生成JWT Token并返回给前端:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private UserDetailsService userDetailsService;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody AuthRequest authRequest) throws Exception {
try {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword())
);
UserDetails userDetails = userDetailsService.loadUserByUsername(authRequest.getUsername());
String token = jwtTokenUtil.generateToken(userDetails);
return ResponseEntity.ok(new AuthResponse(token));
} catch (Exception e) {
throw new Exception("Incorrect username or password", e);
}
}
}
```
其中,AuthController类中的login方法用于处理登录请求,通过authenticationManager.authenticate方法验证用户名和密码,然后使用JwtTokenUtil生成JWT Token并返回给前端。
阅读全文