Tag Archives: jwt

[Solved] Simple jwt Error: AttributeError: type object ‘BlacklistedToken‘ has no attribute ‘objects

Solution: add in Django setting

'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
    'UPDATE_LAST_LOGIN': False,

For example:

SIMPLE_JWT = {

     'ACCESS_TOKEN_LIFETIME': datetime.timedelta(days=7),
    'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=7),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
    'UPDATE_LAST_LOGIN': False,

}

Two methods of fixing WPF menu bar after scrolling to the top

Recently, there is a requirement in the project:

The menu bar is fixed at the top after scrolling to the top.. This is quite common on the mobile end

Look at the effect:

Let’s take a look at the code. There are not many codes

The first method is as follows:

Write a menu as like as two peas, and hide it on top of the window. When the menu is rolled up to the top, it will be displayed, otherwise hidden. br>

Mainwindow1.xaml is as follows:

<Window x:Class="wpfcore.MainWindow1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:wpfcore"
        mc:Ignorable="d"
        Title="MainWindow1" Height="450" Width="800">
    <Grid>
        <ScrollViewer ScrollChanged="ScrollViewer_ScrollChanged">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="200"/>
                    <RowDefinition Height="auto"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Grid Grid.Row="0" x:Name="banner">
                    <Image Source="D:\bizhi\123\2-9.jpg" Stretch="UniformToFill" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="30" Foreground="White" Text="这是顶部Banner"/>
                </Grid>
                <StackPanel Grid.Row="1" Panel.ZIndex="100" x:Name="menu" Orientation="Horizontal" TextBlock.FontSize="18" Background="LightBlue">
                    <TextBlock Text="Home" Margin="10"></TextBlock>
                    <TextBlock Text="Editor" Margin="10"></TextBlock>
                    <TextBlock Text="Viewer" Margin="10"></TextBlock>
                    <TextBlock Text="Debug" Margin="10"></TextBlock>
                    <TextBlock Text="WPF UI" Margin="10"></TextBlock>
                </StackPanel>
                <Border Height="1000" Grid.Row="22">
                    <Border.Background>
                        <LinearGradientBrush>
                            <GradientStop Color="Red" Offset="0"/>
                            <GradientStop Color="Green" Offset="0.5"/>
                            <GradientStop Color="Blue" Offset="1"/>
                        </LinearGradientBrush>
                    </Border.Background>
                    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="30" Foreground="White" Text="这是顶部Banner"/>
                </Border>
            </Grid>
        </ScrollViewer>
        <StackPanel x:Name="topMenu" VerticalAlignment="Top" Visibility="Hidden" Orientation="Horizontal" TextBlock.FontSize="18" Background="LightBlue">
            <TextBlock Text="Home" Margin="10"></TextBlock>
             <TextBlock Text="Editor" Margin="10"></TextBlock>
             <TextBlock Text="Viewer" Margin="10"></TextBlock>
             <TextBlock Text="Debug" Margin="10"></TextBlock>
            <TextBlock Text="WPF UI" Margin="10"></TextBlock>
        </StackPanel>
    </Grid>
</Window>

Mainwindow1.cs Code:

using System.Windows;


namespace wpfcore
{
    public partial class MainWindow1 : Window
    {
        public MainWindow1()
        {
            InitializeComponent();
        }
        private void ScrollViewer_ScrollChanged(object sender, System.Windows.Controls.ScrollChangedEventArgs e)
        {
            if (e.VerticalOffset > banner.ActualHeight)
            {
                 topMenu.Visibility = Visibility.Visible;
            }
            else
            {
                topMenu.Visibility = Visibility.Hidden;
            }
        }
    }
}

—————Dividing line——————

Second method:

Add render transform to the menu bar. When the menu scrolls to the top, set translatetransform. Yproperty   The same effect was achieved

Mainwindow.xaml code is as follows:

<Window x:Class="wpfcore.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:wpfcore" 
        xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"
        mc:Ignorable="d"
        UseLayoutRounding="True"
        Title="MainWindow" Width="600" Height="340">
    <Grid>
        <ScrollViewer ScrollChanged="ScrollViewer_ScrollChanged">
            <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="200"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <Grid Grid.Row="0" x:Name="banner">
                <Image Source="D:\bizhi\123\2-9.jpg" Stretch="UniformToFill" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="30" Foreground="White" Text="这是顶部Banner"/>
            </Grid>
            <StackPanel Grid.Row="1" Panel.ZIndex="100" x:Name="menu" Orientation="Horizontal" TextBlock.FontSize="18" Background="LightBlue">
                    <StackPanel.RenderTransform>
                        <TranslateTransform x:Name="menuTranslate" Y="0.0"/>
                    </StackPanel.RenderTransform>
                    <TextBlock Text="Home" Margin="10"></TextBlock>
                    <TextBlock Text="Editor" Margin="10"></TextBlock>
                    <TextBlock Text="Viewer" Margin="10"></TextBlock>
                    <TextBlock Text="Debug" Margin="10"></TextBlock>
                    <TextBlock Text="WPF UI" Margin="10"></TextBlock>
                </StackPanel>
            <Border Height="1000" Grid.Row="22">
                <Border.Background>
                    <LinearGradientBrush>
                        <GradientStop Color="Red" Offset="0"/>
                        <GradientStop Color="Green" Offset="0.5"/>
                        <GradientStop Color="Blue" Offset="1"/>
                    </LinearGradientBrush>
                </Border.Background>
                    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="30" Foreground="White" Text="这是顶部Banner"/>
                </Border>
        </Grid>
    </ScrollViewer>
        <StackPanel x:Name="topMenu" VerticalAlignment="Top" Visibility="Hidden" Orientation="Horizontal" TextBlock.FontSize="18" Background="LightBlue">
            <TextBlock Text="Home" Margin="10"></TextBlock>
            <TextBlock Text="Editor" Margin="10"></TextBlock>
            <TextBlock Text="Viewer" Margin="10"></TextBlock>
            <TextBlock Text="Debug" Margin="10"></TextBlock>
            <TextBlock Text="WPF UI" Margin="10"></TextBlock>
        </StackPanel>
    </Grid>
</Window>


Mainwindow.cs Code:

using System.Windows;
using System.Windows.Media;


namespace wpfcore
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }


        private void ScrollViewer_ScrollChanged(object sender, System.Windows.Controls.ScrollChangedEventArgs e)
        {
            menuTranslate.SetValue(TranslateTransform.YProperty, e.VerticalOffset);
            if (e.VerticalOffset > banner.ActualHeight)
            {
                menuTranslate.SetValue(TranslateTransform.YProperty, e.VerticalOffset-banner.ActualHeight);
            }
            else
            {
                menuTranslate.SetValue(TranslateTransform.YProperty, 0.0);
            }
        }
    }
}


Djangorestframework-simplejwt: ‘str‘ object has no attribute ‘decode‘ [Solved]

Problem description

Python v3.6.6Django v3.2.4djangorestframework v3.12.4djangorestframework-simplejwt v4.4.0

When testing the interface after running runserver command, the error of background printing is as follows

Traceback (most recent call last):
  File "D:\Program Files\Python36\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Program Files\Python36\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "D:\Program Files\Python36\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework_simplejwt\views.py", line 27, in post
    serializer.is_valid(raise_exception=True)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\serializers.py", line 220, in is_valid
    self._validated_data = self.run_validation(self.initial_data)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\serializers.py", line 422, in run_validation
    value = self.validate(value)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework_simplejwt\serializers.py", line 75, in validate
    data['refresh'] = str(refresh)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework_simplejwt\tokens.py", line 82, in __str__
    return token_backend.encode(self.payload)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework_simplejwt\backends.py", line 43, in encode
    return token.decode('utf-8')
AttributeError: 'str' object has no attribute 'decode'

terms of settlement

Method 1

Upgrade the djangorestframework simplejwt version to 4.6.0 +

Method 2

Open
D:// program files/Python 36/lib/site packages/rest_ framework_ simplejwt\backends.py

File, edit line 43. take

return token.decode('utf-8')

It can be amended as follows

return token

explain

Realization of springboot authorization verification technology based on JWT

The JWT token permission authentication technology based on Springboot is simply implemented
JWT profile
Json Web Token (JWT) : Json network Token, an open standard based on Json ((RFC 7519) for passing declarations between network application environments. JWT is a lightweight, secure, cross-platform transport format that defines a compact, self-contained way to communicate between two parties using JSON objects to securely transfer information. This information is reliable because of the digital signature.
Implementation steps:
Environmental spring boot
1. Add JWT dependency

 <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.8.1</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

2. Create annotation package </h6 b> under SRC
New custom annotation class JwtToken

package com.qf.tyleryue_one.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface JwtToken {
}

3. Create utils package </h6 b> under SRC
Create a new custom JwtUtils utility class

package com.qf.tyleryue_one.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import jdk.internal.org.objectweb.asm.TypeReference;

import java.util.Date;


public class JwtUtils {
    private final static long EXPIRE_TIME=5*60*1000;
    private final static String SECRECT="Tyler_Yue_key";
    public  static  String sign(String userId){
        Date exipre_date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        JWTCreator.Builder builder = JWT.create();
        builder.withAudience(userId);
        builder.withExpiresAt(exipre_date);
        Algorithm algorithm = Algorithm.HMAC256(SECRECT);
        String sign = builder.sign(algorithm);
        return  sign;
    }

    public  static boolean verifyToken(String token){

        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRECT);
            JWTVerifier build = JWT.require(algorithm).build();
            return  true;
        } catch (Exception e) {
            throw  new RuntimeException("Out of date");
        }
      
    }
}

4. Create new vo package under SRC
Encapsulates an object that returns the user’s token

package com.qf.tyleryue_one.vo;

import com.alibaba.druid.filter.AutoLoad;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


@Data
@AllArgsConstructor
@NoArgsConstructor
public class TokenVo {
    private  String usernaem;
    private String token;
}

5. Example of controller layer user login business login with token </h6 b>

package com.qf.tyleryue_one.controller;

import com.qf.tyleryue_one.entity.VueUser;
import com.qf.tyleryue_one.service.VueUserService;
import com.qf.tyleryue_one.utils.JwtUtils;
import com.qf.tyleryue_one.vo.Msg;
import com.qf.tyleryue_one.vo.TokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;


@Controller
public class VueUserController {
    @Autowired
    private VueUserService vueUserService;

    @RequestMapping(value = "/dealLogin",method = RequestMethod.POST)
    @CrossOrigin
    @ResponseBody
    public Msg login(@RequestBody VueUser vueUser){
        VueUser vueUser1 = vueUserService.selectByUsername(vueUser.getUsername());

        if (vueUser1!=null){
            if (vueUser1.getPassword().equals(vueUser.getPassword())){
                String userid = UUID.randomUUID().toString();
                String token = JwtUtils.sign(userid);
                TokenVo tokenVo = new TokenVo(vueUser.getUsername(), token);
                return new Msg(200,"Logined",tokenVo);

            }else {
                return  new Msg(403,"password wrong",null);
            }
        }else {
            return new Msg(403,"not exsit",null);
        }
    }
}

</ div>